
在建立printWriter实例时(PrintWrite pw = new PrintWrite(fos,,true)),需要用boolean型指定,是不是自动刷新,如果没有指定自动刷新,则需要自己来flush.
呵,呵,要讲清楚啦。
楼主我只要50分额。
用java往文件里面写入文字可以用到java里面的I/O流来实现功能, 一般都是用FileWriter类来实现要求。具体的代码示例如下:
import java.io.BufferedReaderimport java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
/**
* java读写文件
* 读取d:/1.txt文件内容,写入f:/text.txt文件中.
*
* 写入文件换行用fw.write("\r\n")
* 或者fw.write("\n")
* @author young
*
*/
public class FileWriterTest {
// 读写文件
public static void rwFile(){
FileWriter fw = null
BufferedReader br = null
try {
// 定义FileWriter对象,关联文件f:\text.txt,用来向文件写内容
fw = new FileWriter("f:\\text.txt", true)
// 定义bufferedReader对象,用来读取d:\1.txt文件内容
br = new BufferedReader(new InputStreamReader(
new FileInputStream("d:\\1.txt"), "UTF-8"))
String line = null
// 每次读取一行内容,循环读取,读到文件末尾结束
while ((line = br.readLine()) != null) {
System.out.println("文件内容: " + line)
fw.write(line)
// 刷新缓冲流,
fw.flush()
}
// 关闭I/O流
br.close()
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
} finally {
if (fw != null) {
try {
fw.close()
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}
public static void main(String[] args) {
rwFile()
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)