Java写入文件方法汇总

Java写入文件,感兴趣的可以看下面学一学。

writeBytes(String)  write(string.getBytes())

https://blog.csdn.net/xidianliuy/article/details/51579071

1

write = new OutputStreamWriter(new FileOutputStream(htmlFileName),"UTF-8");

BufferedWriter writer=new BufferedWriter(write); 

2

BufferedWriter fw = new BufferedWriter(new FileWriter(htmlFileName));

fw.write(ss);

3.

RandomAccessFile raf = new RandomAccessFile(htmlFileName,"rw") ;

raf.write(ss.getBytes("UTF-8")) ;

4.FileChannel fileChannel = fileOutputStream.getChannel();

https://segmentfault.com/a/1190000021726918

String s = "test";

        FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/test.txt");

        FileChannel fileChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        byteBuffer.put(s.getBytes());

        fileChannel.write(byteBuffer);

        fileOutputStream.close();

https://www.cnblogs.com/w-wfy/p/6411323.html

FileWriter是OutputStreamWriter的子类。

FileWriter缺点是不能指定“编码集”


FileOutputStream 是字节流,它一个字节一个字节的向外边送数据

OutputStreamWrite是字符流,它一个字符一个字符的向外边送数据

它们有什么区别么?

解析:

因为计算机是洋鬼子发明的,它们的英文字符占一个字节,而我们的中文是一个字符,占俩字节。

如果用stream,你读出来的英语再倒也罢了,读出来的中文可就是乱码或者一个个“????”。

如果你用WRITER,就不会有乱码了,明白?


BufferedWriter Buffer是一个缓冲区,为什么要用BUFFER呢?

如果你直接用stream或者writer,你的硬盘可能就是一个字符或者一个字节 读写硬盘一次,

可是你用了Buffer,你的硬盘就是读了一堆数据之后,读写一下硬盘。这样对你硬盘有好处。


相关标签:


评论: