Java源码示例:java.io.FileInputStream
示例1
private void getPropertiesFromFile( Properties props, String fileName )
{
try {
File file = new File( fileName ) ;
if (!file.exists())
return ;
FileInputStream in = new FileInputStream( file ) ;
try {
props.load( in ) ;
} finally {
in.close() ;
}
} catch (Exception exc) {
if (debug)
System.out.println( "ORB properties file " + fileName +
" not found: " + exc) ;
}
}
示例2
/**
*
* Change the job name in the config.properties file
* */
public void changeConfigFileJobName(String job) throws IOException
{
InputStream input = new FileInputStream(_path);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder out = new StringBuilder();
String line, row = null;
while ((line = reader.readLine()) != null) {
row = line.toString();
if(line.toString().contains("jenkins.jobName")){
row = "jenkins.jobName=" + job;
}
out.append(row + "\n");
}
reader.close();
OutputStream output = new FileOutputStream(_path);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
writer.write(out.toString());
writer.close();
}
示例3
public static void convert(File inFile, File outFile) throws IOException {
MMcifParser parser = new SimpleMMcifParser();
SimpleMMcifConsumer consumer = new SimpleMMcifConsumer();
parser.addMMcifConsumer(consumer);
parser.parse(new BufferedReader(new InputStreamReader(new FileInputStream(inFile))));
// now get the protein structure.
Structure cifStructure = consumer.getStructure();
// and write it out as PDB format
PrintWriter pr = new PrintWriter(outFile);
for (Chain c : cifStructure.getChains()) {
// we can override the chain name, the mmCIF chain names might have more than 1 character
c.setName(c.getName().substring(0, 1));
pr.print(c.toPDB());
pr.println("TER");
}
pr.close();
}
示例4
/** Reads the TextColumn data from the given file and stuffs it into a new TextColumn */
private static TextColumn readTextColumn(
String fileName, TableMetadata tableMetadata, ColumnMetadata columnMetadata)
throws IOException {
TextColumn textColumn = TextColumn.create(columnMetadata.getName());
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
int j = 0;
while (j < tableMetadata.getRowCount()) {
textColumn.append(dis.readUTF());
j++;
}
}
return textColumn;
}
示例5
/**
* 将压缩文件中的内容解压到指定目录中<br>
* 如果<code>baseDir</code>的值为空,则将文件解压到相同的目录中,目录名称为"zipFile_files"
* @param zipFile
* 压缩文件路径
* @param baseDir
* 解压的目标路径,可以为null
* @throws IOException
*/
public static String upZipFile(String zipFile, String baseDir) throws IOException {
File f = new File(zipFile);
if (baseDir == null) {
baseDir = f.getPath() + "_files";
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
ZipEntry ze;
byte[] buf = new byte[1024];
while ((ze = zis.getNextEntry()) != null) {
File outFile = getRealFileName(baseDir, ze.getName());
FileOutputStream os = new FileOutputStream(outFile);
int readLen = 0;
while ((readLen = zis.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
os.close();
}
zis.close();
return baseDir;
}
示例6
/**
* Compile the protobuf and generate descriptor file.
*
* @param protoPath protobuf file path
* @param descriptorPath descriptor file path
* @return {@link DescriptorProtos.FileDescriptorSet} object
*/
private static DescriptorProtos.FileDescriptorProto generateRootFileDescriptor(String protoPath,
String descriptorPath) {
String command = new ProtocCommandBuilder
(protoPath, resolveProtoFolderPath(protoPath), descriptorPath).build();
generateDescriptor(command);
File initialFile = new File(descriptorPath);
try (InputStream targetStream = new FileInputStream(initialFile)) {
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
//to register all custom extensions in order to parse properly
ExtensionHolder.registerAllExtensions(extensionRegistry);
DescriptorProtos.FileDescriptorSet set = DescriptorProtos.FileDescriptorSet.parseFrom(targetStream,
extensionRegistry);
logger.debug("Descriptor file is parsed successfully. file:" , descriptorPath);
if (set.getFileList().size() > 0) {
return set.getFile(0);
}
} catch (IOException e) {
throw new CLIInternalException("Error reading generated descriptor file '" + descriptorPath + "'.", e);
}
return null;
}
示例7
@Test
public void testDataWriting() throws Exception {
long byteAm = 100;
File fn = getTestFile();
DataWriter writer = new DataWriter(rnd);
FileOutputStream fs = new FileOutputStream(fn);
GenerateOutput ostat = writer.writeSegment(byteAm, fs);
LOG.info(ostat);
fs.close();
assertTrue(ostat.getBytesWritten() == byteAm);
DataVerifier vf = new DataVerifier();
FileInputStream fin = new FileInputStream(fn);
VerifyOutput vfout = vf.verifyFile(byteAm, new DataInputStream(fin));
LOG.info(vfout);
fin.close();
assertEquals(vfout.getBytesRead(), byteAm);
assertTrue(vfout.getChunksDifferent() == 0);
}
示例8
private File copyServiceToFileSystem(String resourceName, String fileName) throws IOException {
File file = new File(System.getProperty("basedir") + File.separator + "target" + File.separator + fileName);
if (file.exists()) {
FileUtils.deleteQuietly(file);
}
FileUtils.touch(file);
OutputStream os = FileUtils.openOutputStream(file);
InputStream is = new FileInputStream(
FrameworkPathUtil.getSystemResourceLocation() + File.separator + "artifacts" + File.separator + "AXIS2"
+ File.separator + "config" + File.separator + resourceName);
if (is != null) {
byte[] data = new byte[1024];
int len;
while ((len = is.read(data)) != -1) {
os.write(data, 0, len);
}
os.flush();
os.close();
is.close();
}
return file;
}
示例9
/**
* Loads the application properties and populates a java.util.Properties
* instance.
*
* @param servletConfig
* The ServletConfig used to locate the application property
* file.
* @return The application properties.
*/
private Properties loadApplicationProperties(ServletConfig servletConfig) {
// read application properties from servlet context
ServletContext ctx = servletConfig.getServletContext();
String path = ctx.getRealPath("/");
String appConfigFile = ctx.getInitParameter(APP_CONFIG_LOCATION);
Properties properties = new Properties();
try {
InputStream is = new FileInputStream(path + appConfigFile);
properties.load(is);
is.close();
LOG.info("Loaded application properties from " + path + appConfigFile);
} catch (IOException e) {
LOG.error("Unable to load application properties from " + path + appConfigFile, e);
}
return properties;
}
示例10
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
public InputStream newInputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
return null;
}
try {
return new FileInputStream(entry.getCleanFile(index));
} catch (FileNotFoundException e) {
return null;
}
}
}
示例11
/**
* Given a file, find only the properties that are setable by AppletViewer.
*
* @param inFile A Properties file from which we select the properties of
* interest.
* @return A Properties object containing all of the AppletViewer
* user-specific properties.
*/
private Properties getAVProps(File inFile) {
Properties avProps = new Properties();
// read the file
Properties tmpProps = new Properties();
try (FileInputStream in = new FileInputStream(inFile)) {
tmpProps.load(new BufferedInputStream(in));
} catch (IOException e) {
System.err.println(lookup("main.err.prop.cantread", inFile.toString()));
}
// pick off the properties we care about
for (int i = 0; i < avDefaultUserProps.length; i++) {
String value = tmpProps.getProperty(avDefaultUserProps[i][0]);
if (value != null) {
// the property exists in the file, so replace the default
avProps.setProperty(avDefaultUserProps[i][0], value);
} else {
// just use the default
avProps.setProperty(avDefaultUserProps[i][0],
avDefaultUserProps[i][1]);
}
}
return avProps;
}
示例12
public static String readTxtFile(String filePath) {
try {
String encoding = "UTF-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) { //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
StringBuffer sb = new StringBuffer();
while ((lineTxt = bufferedReader.readLine()) != null) {
sb.append(lineTxt).append("\n");
}
read.close();
return sb.toString();
} else {
log.warn("文件{}配置有误,找不到指定的文件", file);
}
} catch (Exception e) {
log.error("读取文件内容出错", e);
}
return null;
}
示例13
public static MxisdConfig loadFromFile(String path) throws IOException {
File f = new File(path).getAbsoluteFile();
log.info("Reading config from {}", f.toString());
Representer rep = new Representer();
rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
rep.getPropertyUtils().setAllowReadOnlyProperties(true);
rep.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
try (FileInputStream is = new FileInputStream(f)) {
MxisdConfig raw = yaml.load(is);
log.debug("Read config in memory from {}", path);
// SnakeYaml set objects to null when there is no value set in the config, even a full sub-tree.
// This is problematic for default config values and objects, to avoid NPEs.
// Therefore, we'll use Gson to re-parse the data in a way that avoids us checking the whole config for nulls.
MxisdConfig cfg = GsonUtil.get().fromJson(GsonUtil.get().toJson(raw), MxisdConfig.class);
log.info("Loaded config from {}", path);
return cfg;
} catch (ParserException t) {
throw new ConfigurationException(t.getMessage(), "Could not parse YAML config file - Please check indentation and that the configuration options exist");
}
}
示例14
public static byte[] getFileDigest(FileInputStream fin) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA256");
byte[] buffer = new byte[4096];
int read = 0;
while ((read = fin.read(buffer, 0, buffer.length)) != -1) {
digest.update(buffer, 0, read);
}
return digest.digest();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
示例15
/**
* Attempt to load a GCR compatible RegistryAuthSupplier based on a few conditions:
* <ol>
* <li>First check to see if the environemnt variable DOCKER_GOOGLE_CREDENTIALS is set and points
* to a readable file</li>
* <li>Otherwise check if the Google Application Default Credentials can be loaded</li>
* </ol>
* Note that we use a special environment variable of our own in addition to any environment
* variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need for
* the user to use the latter env var for some other purpose in their build.
*
* @return a GCR RegistryAuthSupplier, or null
* @throws IOException if an IOException occurs while loading the credentials
*/
@Nullable
private RegistryAuthSupplier googleContainerRegistryAuthSupplier() throws IOException {
GoogleCredentials credentials = null;
final String googleCredentialsPath = System.getenv("DOCKER_GOOGLE_CREDENTIALS");
if (googleCredentialsPath != null) {
final File file = new File(googleCredentialsPath);
if (file.exists()) {
try (FileInputStream inputStream = new FileInputStream(file)) {
credentials = GoogleCredentials.fromStream(inputStream);
getLog().info("Using Google credentials from file: " + file.getAbsolutePath());
}
}
}
// use the ADC last
if (credentials == null) {
try {
credentials = GoogleCredentials.getApplicationDefault();
getLog().info("Using Google application default credentials");
} catch (IOException ex) {
// No GCP default credentials available
getLog().debug("Failed to load Google application default credentials", ex);
}
}
if (credentials == null) {
return null;
}
return ContainerRegistryAuthSupplier.forCredentials(credentials).build();
}
示例16
private static void reloadClass(File f, Instrumentation inst) throws Exception {
byte[] targetClassFile = new byte[(int) f.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readFully(targetClassFile);
dis.close();
DynamicClassLoader myLoader = new DynamicClassLoader();
Class<?> targetClazz = myLoader.findClass(targetClassFile);
System.err.println("目标class类全路径为" + targetClazz.getName());
ClassDefinition clazzDef = new ClassDefinition(Class.forName(targetClazz.getName()), targetClassFile);
inst.redefineClasses(clazzDef);
System.err.println("重新定义" + targetClazz.getName() + "完成!!");
}
示例17
/**
* Load and evaluate the specified JavaScript file.
*
* @param path Path to UTF-8 encoded JavaScript file.
*
* @return Last evaluation result (discarded.)
*/
@SuppressWarnings("resource")
private Object load(String path) {
try {
FileInputStream file = new FileInputStream(path);
InputStreamReader input = new InputStreamReader(file, "UTF-8");
return engine.eval(input);
} catch (FileNotFoundException | UnsupportedEncodingException | ScriptException ex) {
ex.printStackTrace();
}
return null;
}
示例18
@Test
public void testSequentialWriter() throws IOException
{
File file = FileUtils.createTempFile("dataoutput", "test");
final SequentialWriter writer = new SequentialWriter(file, 32);
DataOutputStreamAndChannel write = new DataOutputStreamAndChannel(writer, writer);
DataInput canon = testWrite(write);
write.flush();
write.close();
DataInputStream test = new DataInputStream(new FileInputStream(file));
testRead(test, canon);
test.close();
Assert.assertTrue(file.delete());
}
示例19
private void readCertificate(String publicKeyPath) throws CertificateException, IOException {
CertificateFactory fact = CertificateFactory.getInstance("X.509");
try (FileInputStream fileInputStream = new FileInputStream(publicKeyPath)) {
certificate = (X509Certificate) fact.generateCertificate(fileInputStream);
publicKey = certificate.getPublicKey();
}
}
示例20
public static void setup(Config config)
throws java.io.IOException
{
if (config.isSet("log_config_file"))
{
try
{
log_props.load(new FileInputStream(config.get("log_config_file")));
LogManager.getLogManager().readConfiguration(new FileInputStream(config.get("log_config_file")));
}
catch (Exception e)
{
System.out.println("FAILED TO INITIALIZE LOGGING: " + e);
}
}
else
{
log_props.setProperty(".level", "FINE");
log_props.setProperty("io.level", "SEVERE");
}
//listLoggers();
}
示例21
@Test
public void shouldReplaceWithPackagedCommandRepositoryWhenOlderRepoExists() throws Exception {
File versionFile = TestFileUtil.writeStringToTempFileInFolder("default", "version.txt", "10.1=10");
File randomFile = TestFileUtil.createTestFile(versionFile.getParentFile(), "random");
File defaultCommandRepoDir = versionFile.getParentFile();
initializer.usePackagedCommandRepository(new ZipInputStream(new FileInputStream(getZippedCommandRepo("12.4=12"))), defaultCommandRepoDir);
assertThat(defaultCommandRepoDir.exists(), is(true));
assertThat(FileUtils.readFileToString(new File(defaultCommandRepoDir, "version.txt"), UTF_8), is("12.4=12"));
assertThat(new File(defaultCommandRepoDir, "snippet.xml").exists(), is(true));
assertThat(new File(defaultCommandRepoDir, randomFile.getName()).exists(), is(false));
}
示例22
private void importBot(String botId, Integer version) throws IOException {
String zipFilename = prepareZipFilename(botId, version);
String targetZipPath = FileUtilities.buildPath(tmpPath, zipFilename);
deleteFileIfExists(Paths.get(targetZipPath));
this.zipArchive.createZip(tmpPath, targetZipPath);
importService.importBot(new FileInputStream(targetZipPath), null);
}
示例23
public void executeCanonicalXml(String[] args) throws FHIRException, IOException {
FileInputStream in;
File source = new CSFile(args[1]);
File dest = new CSFile(args[2]);
if (!source.exists())
throw new FHIRException("Source File \""+source.getAbsolutePath()+"\" not found");
in = new CSFileInputStream(source);
XmlParser p = new XmlParser();
Resource rf = p.parse(in);
XmlParser cxml = new XmlParser();
cxml.setOutputStyle(OutputStyle.NORMAL);
cxml.compose(new FileOutputStream(dest), rf);
}
示例24
public static State deserialize(File f) throws FileNotFoundException,
IOException, ClassNotFoundException {
ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
State zone = (State) os.readObject();
os.close();
return zone;
}
示例25
public static SearchOptions read(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
SearchOptions searchOptions = null;
// Deserialize from a file
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
try {
// Deserialize the object
searchOptions = (SearchOptions) in.readObject();
} finally {
in.close();
}
return searchOptions;
}
示例26
@Override
protected Object parse(Resource resource, Class<?> pluginConfigClass)
throws Exception{
InputStream input = new FileInputStream(resource.getFile());
YAMLParser yamlParser = yamlFactory.createParser(input);
final JsonNode node = objectMapper.readTree(yamlParser);
if(node == null){
return pluginConfigClass.newInstance();
}
TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node);
return objectMapper.readValue(treeTraversingParser, pluginConfigClass);
}
示例27
private static String getTestFileAsString(File file) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(file));
return XMLConverter.convertToString(doc, false)
.replace("<!-- Copyright FUJITSU LIMITED 2017-->", "");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例28
/**
* Create InputStream for known data
* @param uri of data
* @return InputStream
*/
@Override
public InputStream getDataInputStream(SailfishURI uri) {
String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE);
if (resource == null) {
throw new RuntimeException("No data found for URI: " + uri);
}
try {
return new FileInputStream(workspaceDispatcher.getFile(FolderType.ROOT, resource));
} catch (FileNotFoundException e) {
throw new ScriptRunException("Could not create data input stream [" + resource + "]", e);
}
}
示例29
private static void verifyContents(File file) {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] contents = FILE_CONTENTS.getBytes();
int read, count = 0;
while ((read = fis.read()) != -1) {
if (read != contents[count++]) {
fail("file contents have been altered");
return;
}
}
} catch (IOException ioe) {
unexpected(ioe);
}
}
示例30
/**
* Prints a disassembled view of the given class to the standard output. <p>
* Usage: TraceClassVisitor [-debug] <fully qualified class name or class
* file name >
*
* @param args the command line arguments.
*
* @throws Exception if the class cannot be found, or if an IO exception
* occurs.
*/
public static void main(final String[] args) throws Exception {
int i = 0;
int flags = ClassReader.SKIP_DEBUG;
boolean ok = true;
if (args.length < 1 || args.length > 2) {
ok = false;
}
if (ok && "-debug".equals(args[0])) {
i = 1;
flags = 0;
if (args.length != 2) {
ok = false;
}
}
if (!ok) {
System.err.println("Prints a disassembled view of the given class.");
System.err.println("Usage: TraceClassVisitor [-debug] "
+ "<fully qualified class name or class file name>");
return;
}
ClassReader cr;
if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1
|| args[i].indexOf('/') > -1)
{
cr = new ClassReader(new FileInputStream(args[i]));
} else {
cr = new ClassReader(args[i]);
}
cr.accept(new TraceClassVisitor(new PrintWriter(System.out)),
getDefaultAttributes(),
flags);
}