Read/Write string to file.
try(BufferedWriter w = new BufferedWriter(new FileWriter(path,true)))
{ w.write(string); }
String srcXml = new String(Files.readAllBytes(new File(file).toPath()), Charset.forName("UTF-8"));
Copy content to another file line by line, using try-with-resource and streams.
try (Stream<String> stream = Files.lines(Paths.get(fileName));
BufferedWriter writer = Files.newBufferedWriter(Paths.get(outfileName))) {
stream.forEach(line -> {
try {
writer.write(line);
} catch (IOException e1) {
e1.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
File Streams
Reading a file with InputStreamReader and FileInputStream
InputStreamReader input = new InputStreamReader(new FileInputStream("foo.txt"));
InputStream reads a raw socket (8 bit) data, InputStreamReader transform data to some encoding, BufferedReader is a wrapper for xxxReader.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
/**
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
/**
- Where is the class loaded from, file:/path/myclass.class
- */
URL location = String.class.getResource('/'+klass.getName().replace('.', '/')+".class");