Java IO随机流 读取乱码和自动换行

public class TsetWiteTeade {

public static void main(String[] args) {
    TsetWiteTeade tw = new TsetWiteTeade();
    tw.writeToFileRead(new File("D:\\a学习\\javaIO\\IO.txt"));
}

public void writeToFileRead(File file) {
    RandomAccessFile raf = null;
    Scanner sc = null;
    try {
        raf = new RandomAccessFile(file, "rw");
        raf.setLength(0);    //清空文件内容
        sc = new Scanner(System.in);
        String str = null;
        int len = 0;
        System.out.println("请输入要写入文件的内容(以#号结束):");
        byte[] datas = null;
        while (!(str = sc.nextLine()).equals("#")) {
            datas = str.getBytes();            //转字节,防止中文乱码
            raf.write(datas);
            raf.write("\n".getBytes());        //设置转行,将"\n"转字符
        }
        System.out.println("写入成功");
        raf.seek(0);//设置指针到最前,因为前面写入会让指针指向末尾        
        while (raf.getFilePointer() < raf.length()) {
            len = raf.read(datas);
            System.out.println(new String(datas,0,len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (sc != null) {
            sc.close();
        }
    }
}

}

img

输出的时候加下编码格式即可