FileOutputStream类的构造方法如下:
public FileOutputStream(File file)throws FileNotFoundException
public class Test{
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建
String str="Hello World";
byte[] b=str.getBytes();
out.write(b);//因为是字节流,所以要转化成字节数组进行输出
out.close();
}
}
public class Test {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建
String str="Hello World";
byte[] b=str.getBytes();
for(int i=0;i<b.length;i++){
out.write(b[i]);
}
out.close();
}
}
以上输出只会进行覆盖,如果要追加的话,请看FileOutputStream类的另一个构造方法:
public FileOutputStream(File file,boolean append)throws FileNotFoundException
在构造方法中,如果将append的值设置为true,则表示在文件的末尾追加内容。
public class Test11 {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
OutputStream out=new FileOutputStream(f,true);//追加内容
String str="\r\nHello World";
byte[] b=str.getBytes();
for(int i=0;i<b.length;i++){
out.write(b[i]);
}
out.close();
}
}