JAVA IO - FileWriter&FileReader

本文介绍了Java中FileWriter和FileReader的使用方法,并对比了它们与FileOutputStream和FileInputStream的区别。通过示例代码展示了如何利用FileWriter将字符串写入文件及FileReader从文件中读取内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FileWriter 本身是FileOutputStream的一个包装器,将使用默认的编码格式输出chars. FileWriter的构造函数有一个可以表示如果文件已存在,是否向文件中追加的参数。

FileWriter一般用来将连续的字符串输出到文件中, 要我们自己调用flush方法才会将字符串写入文件中。

当然FileWriter和FileOutputStream都可以向文件中写入内容,后者更底层一些,前者倾向于字符串的输出。

 FileWriter is meant for writing streams of characters. It will use the default character encoding and the default byte-buffer size. In other words, it is a wrapper class of FileOutputStream for convenience. Therefore, to specify these values yourself, consider using a FileOutputStream.

 

FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file.

So if you want to handle binary data such as image file as in your case, you should be using FileOutputStream instead of FileWriter.

import java.io.FileWriter;
import java.io.Writer;

public class WriterTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			Writer writer = new FileWriter("helloworld.txt");
			String str = "hello test1";
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (Exception e) {
            e.printStackTrace();
		}
	}

}

 

类似的FileReader和FileInputStream也有类似的关系

Whether to use streams of bytes or characters? It really depends. Both have buffers. InputStream/OutputStream provide more flexibility, but will make your “simple” program complex. On the other hand, FileWriter/FileReader give a neat solution but you lose the control.

importjava.io.FileReader;
importjava.io.IOException;
importjava.io.Reader;
 
publicclassFileOperationTest {
 
  publicstaticvoidmain(String[] args)
      throwsIOException {
    Reader in =newFileReader("helloworld.txt");
    charcs[] =newchar[1024];
    intlen = -1;
    while((len = in.read(cs)) != -1) {
      System.out.println(newString(cs,0, len));
    }
    in.close();
  }
}

 

转载于:https://my.oschina.net/u/138995/blog/191470

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值