Java学习:IO流JFileChooser类、RandomAccessFile类的简单应用(读取txt文件并打印在控制台)
部分结果演示:
代码实例:
import javax.swing.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class ReaderTest {
public static void main(String[] args) {
System.out.print("欢迎使用,请问是要导入新小说还是查看书库的小说? (输入1:导入新小说 输入2:直接进入书库 输入3:退出本系统)\n请输入:");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
try {
if (i == 1) {
JFileChooser fileChooser = new JFileChooser();// 创建一个JFileChooser实例
String line = null;// 行
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();// 获取对话框点击的文件
RandomAccessFile raf = new RandomAccessFile(file,"r");
while ((line = raf.readLine()) != null) {// 按行读取文档
line = new String(line.getBytes("8859_1"), StandardCharsets.UTF_8);// 编码转化
System.out.println(line);
}
}
}
if (i == 3) {
System.exit(0);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("感谢使用");
}
}
}
**关于编码转化的疑问**
有时候,为了让中文字符适应某些特殊要求(如http header头要求其内容必须为iso8859-1编码),可能会通过将中文字符按照字节方式来编码的情况,如
String s_iso88591 = new String("深".getBytes("UTF-8"),"ISO8859-1"),
这样得到的s_iso8859-1字符串实际是三个在 ISO8859-1中的字符,在将这些字符传递到目的地后,目的地程序再通过相反的方式String s_utf8 = new String(s_iso88591.getBytes("ISO8859-1"),"UTF-8")来得到正确的中文汉字“深”。这样就既保证了遵守协议规定、也支持中文。