If you're simply outputting text, rather than any binary data, the following will work:
CopyPrintWriter out = new PrintWriter("filename.txt");
Then, write your String to it, just like you would to any output stream:
Copyout.println(text);
You'll need exception handling, as ever. Be sure to close the output stream when you've finished writing.
Copyout.close()
If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:
Copytry (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
You will still need to explicitly throw the java.io.FileNotFoundException as before.
Videos
If you're simply outputting text, rather than any binary data, the following will work:
CopyPrintWriter out = new PrintWriter("filename.txt");
Then, write your String to it, just like you would to any output stream:
Copyout.println(text);
You'll need exception handling, as ever. Be sure to close the output stream when you've finished writing.
Copyout.close()
If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:
Copytry (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
You will still need to explicitly throw the java.io.FileNotFoundException as before.
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
Copystatic void writeStringToFile(File file, String data, Charset charset)
which allows you to write text to a file in one method call:
CopyFileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));
You might also want to consider specifying the encoding for the file as well.
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample: `
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`