Read and write file in Java
Read file is at the first part and write file is at the second part. Try it :)
This example is at Learn Your Java From Here: Read and write file
There are more example or Java learning in Learn Your Java From Here
Code Java:
// get which file you want to read and write
File file = new File("D://test.txt");
try {
// check whether the file is existed or not
if (file.exists()) {
// create a new file if the file is not existed
file.createNewFile();
}
// new a writer and point the writer to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
// writer the content to the file
writer.write("I write something to a file.");
// always remember to close the writer
writer.close();
writer = null;
} catch (IOException e) {
e.printStackTrace();
}
try {
// new a reader and point the reader to the file
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "";
System.out.println("Content of the file\n================================");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
reader = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Re: Read and write file in Java
Thanks for the tip. However the statements that set null reference to the reader and writer are redundant.