When writing Java programs, I often encounter situations where I need to read txt or write txt files, but because I have to define many variables, I often can't remember them, so I have to check them every time. I will sort them out here. It is simple and easy to use, and it is easy to understand!
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 { // Prevent file creation or reading failure, use catch to catch errors and print, you can also throw/* to read in TXT file*/String pathname = "D://twitter//13_9_6//dataset//en//input.txt"; // Absolute path or relative path is OK, here is the absolute path. When writing to a file, the relative path is demonstrated. File filename = new File(pathname); // You want to read the input of the above path. txt file InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // Create an input stream object readerBufferedReader br = new BufferedReader(reader); // Create an object that converts the file content into a language that can be understood by the computer String line = "";line = br.readLine(); while (line != null) {line = br.readLine(); // Read one line of data at a time}/* Write to the Txt file*/File writename = new File(".//result//en//output.txt"); // Relative path, if not, a new output is to be created. txt file writename.createNewFile(); // Create a new file BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write("I will write to the file/r/n"); // /r/n is a line break out.flush(); // Press the content of the buffer into the file out.close(); // Finally remember to close the file} catch (Exception e) {e.printStackTrace();}}}}The above simple example of Java reading txt files and writing txt files is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.