java逐⾏写⼊txt⽂件内容_在Java中怎样逐⾏地写⽂件?下边是写东西到⼀个⽂件⾥的Java代码。
执⾏后每⼀次,⼀个新的⽂件被创建,⽽且之前⼀个也将会被新的⽂件替代。这和给⽂件追加内容是不同的。
public static void writeFile1() throws IOException {
File fout = new File("");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i = 0; i < 10; i++) {
bw.write("something");
}
bw.close();
}
这个样例使⽤的是FileOutputStream,你也能够使⽤FileWriter 或PrintWriter。假设是针对⽂本⽂件的操作是全然绰绰有余的。
使⽤FileWriter:
public static void writeFile2() throws IOException {
FileWriter fw = new FileWriter("");
for (int i = 0; i < 10; i++) {
fw.write("something");
}
fw.close();
}使⽤PrintWriter:
public static void writeFile3() throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter(""));
for (int i = 0; i < 10; i++) {
pw.write("something");
}
pw.close();
}使⽤OutputStreamWriter:
public static void writeFile4() throws IOException {
File fout = new File("");
FileOutputStream fos = new FileOutputStream(fout);
OutputStreamWriter osw = new OutputStreamWriter(fos);
for (int i = 0; i < 10; i++) {
osw.write("something");
}
osw.close();
}摘⾃Java⽂档:
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.
FileWriter针对写字符⽂件是⼀个⾮常⽅便的类。这个类的构造⽅法如果默认的字符编码和默认的字节缓冲区都是能够接受的。
如果要指定编码和字节缓冲区的长度,须要构造OutputStreamWriter。
PrintWriter
prints formatted representations of objects to a text-output stream.This class implements all of the print methods found in PrintStream.It
java怎么编写does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
PrintWriter打印格式化对象的表⽰到⼀个⽂本输出流。这个类实现了全部在PrintStream中的打印⽅法。
它不包括⽤于写⼊原始字节,由于⼀个程序应该使⽤未编码的字节流。
主要差别在于,PrintWriter提供了⼀些额外的⽅法来格式化。⽐如println和printf。
此外,万⼀遇到不论什么的I/O故障FileWriter会抛出IOException。PrintWriter的⽅法不抛出IOException异常,⽽是他们设⼀个布尔标志值,能够⽤这个值来检測是否出错(checkError())。
PrintWriter在数据的每⼀个字节被写⼊后⾃⼰主动调⽤flush
。⽽FileWriter,调⽤者必须採取⼿动调⽤flush.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论