Java : Read and Write to a file
The code below show you how you can read a file using Java:
Code for Writing to a file:
By using a buffered stream, you can dramatically improve the performance of I/O operations. We also use the try-with-resources for automatically closes the object and releases its resources.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Path path = Paths.get("myFile.txt"); | |
if(Files.exists(path)){ | |
File file = path.toFile(); | |
try(BufferedReader in = new BufferedReader( | |
new FileReader(file))){ | |
String line = in.readLine(); | |
while(line != null){ | |
System.out.println(line); | |
line = in.readLine(); | |
} | |
} catch(IOException ex){ | |
//do something with exception | |
} | |
} |
Code for Writing to a file:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Path path = Paths.get("myFile.txt"); | |
if(Files.exists(path)){ | |
File file = path.toFile(); | |
try(PrintWriter out = new PrintWriter( | |
new BufferedWriter( | |
new FileWriter(file)))){ | |
out.print("something interesting..."); | |
} catch(IOException ex){ | |
//do something with exception | |
} | |
} |
By using a buffered stream, you can dramatically improve the performance of I/O operations. We also use the try-with-resources for automatically closes the object and releases its resources.
Comments
Post a Comment