In file operations, an error called IOEception may occur when accessing a file, so it is good to handle exceptions.
A glossary is attached at the bottom.
As part of my Java study, I started posting because I wanted to output my knowledge. If you have any mistakes, please point them out!
The classes to import are FIle, FileReader, BufferedReader. The flow is ** File selection → Registration → Buffering → Read → Output **.
First, create a File object to select the file to use this time. Enter the file name you want to specify in the argument.
qiita.rb
File file = new File("file name");
Next, create a FileReader object to register the selected file. (Here, registration is like a declaration to read a file.) Put a File object in the argument.
qiita.rb
FileReader fr = new FileReader(file);
Furthermore, buffering is performed by creating a BufferedReader object so that processing can be performed efficiently. Put the FileReader object in the argument.
qiita.rb
BufferedReader br = new BufferedReader(fr);
Read the file contents using the ReadLine method of BufferedReader. The readLine method reads the text line by line and returns null when it reaches the end.
In order to output the read sentence, substitute the statement obtained by the readLine method into the character string variable in the while statement and output it.
qiita.rb
String str = "" ;
String data ;
while((data = br.readLine()) != null) {
str+=data;
}
System.out.println(str);
The classes to import are FIleWriter, PrintWriter, BufferedWriter. The flow is ** File selection → Registration + Buffering → Write → Save **.
When writing to a file, create a FileWriter object and select the file. Enter the file name you want to select in the first argument. If you want to add characters in addition to writing / overwriting the file, enter true in the second argument.
qiita.rb
FileWriter fw = new FileWriter("file name",true);
After that, create a PrintWriter object to register the file to be written. Define BufferedWriter object with argument. Put the FileWriter object in the argument of the BufferedWriter object.
qiita.rb
PrintWriter pw = new PrintWriter(new BufferedWriter(fw));
You can write a string using PrintWriter's println method. Enter the character string you want to write in the argument.
Finally, you can save the written string to a file by using PrintWriter's close method.
qiita.rb
pw.println("The character string you want to write");
pw.close();
Store up to a certain amount of data in memory and execute a processing instruction when it is accumulated.
Normally, Reader and Writer classes read and write data in streams, but if the amount of data is large, processing will increase and performance will be poor. Therefore, buffering is used.
Processing data in character units and byte units.
Set in advance what kind of processing should be performed when an error occurs. Use a try-catch statement.
Recommended Posts