Java读写一个包含字母数字的txt文件的正确编码方式及代码
时间: 2024-03-13 18:44:13 浏览: 47
Java读写.txt文件
针对包含字母数字的txt文件,一般情况下使用UTF-8编码即可。
以下是Java读取和写入txt文件的代码示例:
读取txt文件:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadTxt {
public static void main(String[] args) {
String filePath = "test.txt"; // 文件路径
File file = new File(filePath);
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
写入txt文件:
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class WriteTxt {
public static void main(String[] args) {
String filePath = "test.txt"; // 文件路径
File file = new File(filePath);
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write("Hello, world!");
bufferedWriter.newLine(); // 换行
bufferedWriter.write("你好,世界!");
bufferedWriter.flush();
bufferedWriter.close();
outputStreamWriter.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
需要注意的是,以上代码中的文件路径需要根据实际情况进行修改。
阅读全文