Java IO流处理中常见错误:文件读写乱码问题示例
在Java的IO流处理中,常见的错误之一就是文件读写时出现乱码。以下是一个典型的示例:
创建一个包含非ASCII字符的文件:
public class Main {
public static void main(String[] args) {
// 创建一个UTF-8编码的字符串
String content = "你好,世界!こんにちは、世界!";
// 将内容写入文件(假设文件名为test.txt)
try (FileWriter writer = new FileWriter("test.txt", false, StandardCharsets.UTF_8))) {
writer.write(content);
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
e.printStackTrace();
}
}
}
打开文件并读取内容:
```java
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(“test.txt”)))) {
String line;
while ((line = reader.readLine()) != null)) {
// 处理读取到的每一行
System.out.println(line);
}
} catch (IOException e) {
System.err.println(“Error reading file: “ + e.getMessage());
e.printStackTrace();
}
}
}
```
- 处理乱码:
在这个示例中,由于文件和处理内容时都使用了UTF-8编码,所以读写过程不会出现乱码问题。如果文件使用了其他字符集(如GBK),在读取和输出时可能会出现乱码,需要进行相应的转换。
还没有评论,来说两句吧...