In Java, FileOutputStream is an bytes stream class to handle the raw binary data. To write it, you have to convert the data into bytes, see below example。
以二进制的方式写入数据到文件,完整例子如下:
- package org.hnrsc.io;
-
-
import java.io.File;
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
-
//
-
public class JavaFileIO {
-
-
public static void main(String[] args) {
-
try {
-
-
String content = "this is text content..";
-
File file = new File("myfile1.txt");
-
-
//if file doesn't exists , then create it
-
FileOutputStream fop = new FileOutputStream(file);
-
//get the content in bytes
-
fop.write(content.getBytes());
-
fop.flush();
-
fop.close();
-
-
System.out.println("Done.");
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
In Java, BufferedWriter is a character streams class to handle the character data. Unlike bytes stream (convert data into bytes), you can just write the strings, arrays or characters data directly to file.
完整例子如下:
- package org.hnrsc.io;
-
-
import java.io.BufferedWriter;
-
import java.io.File;
-
import java.io.FileWriter;
-
import java.io.IOException;
-
-
//
-
public class JavaFileIO {
-
-
public static void main(String[] args) {
-
try {
-
-
String content = "this is text content..";
-
File file = new File("myfile2.txt");
-
-
if(!file.exists()){
-
file.createNewFile();
-
}
-
FileWriter fw = new FileWriter(file.getName());
-
BufferedWriter bw = new BufferedWriter(fw);
-
bw.write(content);
-
bw.close();
-
-
System.out.println("Done.");
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
java以追加(append)的方式,写入内容到文件:FileWritter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWritter constructor, it will keep the existing content and append the new content in the end of the file.
1. Replace all existing content with new content.
2. Keep the existing content and append the new content in the end of the file.
- new FileWriter(file,true);
阅读(2605) | 评论(0) | 转发(0) |