Java reads the txt file and writes a simple instance of the txt file
- 2020-05-16 06:56:47
- OfStack
When writing Java program, I often encounter the situation that I need to read txt or write txt file. However, because I need to define many variables, I often cannot remember them, so I need to check them every time.
package edu.thu.keyword.test;
import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
public class cin_txt {
static void main(String args[]) {
try { // To prevent file creation or read failure, use catch Catch the error and print it, too throw
/* Read in TXT file */
String pathname = "D:\\twitter\\13_9_6\\dataset\\en\\input.txt"; // You can have either an absolute path or a relative path, and this is the absolute path, and you can show the relative path when you write to a file
File filename = new File(pathname); // To read the above path input . txt file
InputStreamReader reader = new InputStreamReader(
new FileInputStream(filename)); // To establish 1 Two input stream objects reader
BufferedReader br = new BufferedReader(reader); // To establish 1 Object that converts the contents of a file into a language that a computer can read
String line = "";
line = br.readLine();
while (line != null) {
line = br.readLine(); // 1 Time to read 1 Rows of data
}
/* write Txt file */
File writename = new File(".\\result\\en\\output.txt"); // Relative paths, if not established 1 A new one output . txt file
writename.createNewFile(); // Create a new file
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
out.write(" I'll write it to a file \r\n"); // \r\n Is the line
out.flush(); // Press the contents of the cache into the file
out.close(); // Finally, close the file
} catch (Exception e) {
e.printStackTrace();
}
}
}