FileOutputStream :文件输入流用于将数据写入File
FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。
public class FileOutputStreamDemo01 {
public static void main(String[] args) throws IOException {
//创建字节输出流对象
//FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。
FileOutputStream fos = new FileOutputStream("C:\\Users\\PCTC\\Desktop\\file\\fos.txt");
/*
* 1.调用系统功能创建文件
* 2.创建字节流输出对象
* 3.让字节流输出对象指向创建好的文件
* */
//void write(int b) 将指定的字节写入此文件输出流。
fos.write(97);
// fos.write(57);
// fos.write(55);
//最后需要释放资源
//void close() 关闭此文件输出流并释放与此流相关联的任何系统资源。
fos.close();
}
}
void write(int b) 将指定的字节写入此文件输出流。
void write(byte[] b) 将 b.length字节从指定的字节数组写入此文件输出流。
void write(byte[] b, int off, int len) 将 len字节从指定的字节数组开始,从偏移量 off开始写入此文件输出流。
public class FileOutputStreamDemo02 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("C:\\Users\\PCTC\\Desktop\\file\\fos.txt");
// File file = new File("C:\\Users\\PCTC\\Desktop\\file\\fos.txt");
// FileOutputStream fos2 = new FileOutputStream(file);
// FileOutputStream fos3 = new FileOutputStream(new File("C:\\Users\\PCTC\\Desktop\\file\\fos.txt"));
//这种写法实际用法和上面一致
//void write(int b) 将指定的字节写入此文件输出流。
// fos.write(97);
// fos.write(98);
// fos.write(99);
//void write(byte[] b) 将 b.length字节从指定的字节数组写入此文件输出流。
// byte[] bys = {97,98,99,100,110};
// byte[] getBytes(); 返回字符串对应的字节数组
byte[] bys = "12346".getBytes();
// fos.write(bys);
//void write(byte[] b, int off, int len) 将 len字节从指定的字节数组开始,从偏移量 off开始写入此文件输出流。
fos.write(bys,0,bys.length);
//释放资源
fos.close();
}
}
字节流写数据两个问题:
1.字节流如何实现换行
Windows:/r/n
Linux: /n
mac: /r
2.如何追加写入
public FileOutputStream(String name,boolean append)
name - 与系统相关的文件名
append - 如果是 true ,则字节将写入文件的末尾而不是开头
public class FileOutputStreamDemo03 {
public static void main(String[] args) throws IOException {
//创建字节输出流对象
// FileOutputStream fos = new FileOutputStream("C:\\Users\\PCTC\\Desktop\\file\\fos.txt");
FileOutputStream fos = new FileOutputStream("C:\\Users\\PCTC\\Desktop\\file\\fos.txt",true);
//写数据
for (int i = 0; i < 10;i++){
fos.write("hello".getBytes());
fos.write("\n".getBytes());
}
fos.close();
}
}
加入finally来释放资源
public class FileOutputStreamDemo04 {
public static void main(String[] args) {
//加入finally来释放资源
FileOutputStream fos = null;
try {
fos = new FileOutputStream("C:\\Users\\PCTC\\Desktop\\file\\fos.txt");
}catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}