How to Write a File Line by Line in Java?

This post summarizes the classes that can be used to write a file.

1. FileOutputStream
public static void writeFile1() throws IOException {
	File fout = new File("out.txt");
	FileOutputStream fos = new FileOutputStream(fout);
	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
	for (int i = 0; i < 10; i++) {
		bw.write("something");
		bw.newLine();
	}
	bw.close();
}

This example use FileOutputStream, instead you can use FileWriter or PrintWriter which is normally good enough for a text file operations.

2. FileWriter
public static void writeFile2() throws IOException {
	FileWriter fw = new FileWriter("out.txt");
	for (int i = 0; i < 10; i++) {
		fw.write("something");
	}
	fw.close();
}
3. PrintWriter
public static void writeFile3() throws IOException {
	PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));
	for (int i = 0; i < 10; i++) {
		pw.write("something");
	} 
	pw.close();
}
4. OutputStreamWriter
public static void writeFile4() throws IOException {
	File fout = new File("out.txt");
	FileOutputStream fos = new FileOutputStream(fout);
	OutputStreamWriter osw = new OutputStreamWriter(fos);
	for (int i = 0; i < 10; i++) {
		osw.write("something");
	}
	osw.close();
}
5. Their Differences

From Java Doc:

FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

The main difference is that PrintWriter offers some additional methods for formatting such as println and printf. In addition, FileWriter throws IOException in case of any I/O failure. PrintWriter methods do not throws IOException, instead they set a boolean flag which can be obtained using checkError(). PrintWriter automatically invokes flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.

6.Summary

I recommend some website to learn java basic language:
www.runoob.com(a lot of tools you can learn)
how2j.cn(maybe you can learn some latest tools,such as hutools,it`s really very interesting,some course need payment sadly)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值