参数可输入字符串表示的路径或File对象
文件不存在会创建一个新文件,但要保证父级路径存在
若文件已存在,会清空文件
void write (int b) 写一个字节数据
public class aaa {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("a.txt");
fos.write(97);
fos.close();
}
}
void write (byte[ ] b) 写一个字节数组数据
void write (byte[ ] b, int off, int len) 写一个字节数组的一段数据
off 是索引开始的下标, len 是写入的长度
public class aaa {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("a.txt");
byte[] b={97,98,99,100,101};
fos.write(b);//abcde
fos.write(b,1,3);//bcd
//最后结果为 abcdebcd, 因为没有输出换行
fos.close();
}
}
想输出长字串的话,可以把string 转byte[ ]
public class aaa {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("a.txt");
String s="abcde";
// 字符串转 byte数组
byte[] b= s.getBytes();
fos.write(b);
fos.close();
}
}
换行
Windows: \r\n Linux: \n Mac: \r
public class aaa {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("a.txt");
fos.write(97);
//换行
String s="\r\n";
byte[] b= s.getBytes();
fos.write(b);
fos.write(97);
fos.close();
}
}
续写
文件路径后输入 true ,默认为 false
FileOutputStream fos = new FileOutputStream("a.txt",true);
初学者,见解不足,如有错误请指出