一、写数据的三种方式
1、一次写入一个字节
方法:void write(int b)
package com.hidata.devops.paas.demo;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description :
* @Date: 2023-10-12 14:26
*/
public class TestDemo {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\workspace_ruoyi_code\\branch\\hipaas\\paas\\src\\test\\java\\com\\hidata\\devops\\paas\\demo\\a.txt");
fos.write(97);
fos.close();
}
}
2、一次写入一个字节数组
方法:void write(byte[] b)
package com.hidata.devops.paas.demo;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description :
* @Date: 2023-10-12 14:26
*/
public class TestDemo {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\workspace_ruoyi_code\\branch\\hipaas\\paas\\src\\test\\java\\com\\hidata\\devops\\paas\\demo\\a.txt");
byte[] bytes = {97,98,99,100,101};
fos.write(bytes);
fos.close();
}
}
3、一次写入一个字节数组的一部分
方法:void write(byte[] b,int off,int len)
其中:
- 参数一:数组
- 参数二:起始索引
- 参数三:个数
package com.hidata.devops.paas.demo;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description :
* @Date: 2023-10-12 14:26
*/
public class TestDemo {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\workspace_ruoyi_code\\branch\\hipaas\\paas\\src\\test\\java\\com\\hidata\\devops\\paas\\demo\\a.txt");
byte[] bytes = {97,98,99,100,101};
fos.write(bytes,0,2);
fos.close();
}
}
二、换行
- 各个操作系统的换行符号:
- windows:\r\n
- Linux:\n
- Mac:\r
注意:
- 在windows系统中,java对回车换行进行了优化,虽然完整的是\r\n,但是我们写其中一个\r或者\n,java也可以实现换行,因为java在底层会自动补全
package com.hidata.devops.paas.demo;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description :
* @Date: 2023-10-12 14:26
*/
public class TestDemo {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\workspace_ruoyi_code\\branch\\hipaas\\paas\\src\\test\\java\\com\\hidata\\devops\\paas\\demo\\a.txt");
fos.write(97);
String wrap = "\r\n";
fos.write(wrap.getBytes());
fos.write(98);
fos.close();
}
}
三、续写
想要每一次写入数据,不会覆盖之前的数据,我们可以加入第二个参数,方法如下:
public FileOutputStream(String name, boolean append)
参数 append,如果为true,表示继续追加,false是直接覆盖
package com.hidata.devops.paas.demo;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description :
* @Date: 2023-10-12 14:26
*/
public class TestDemo {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\a.txt",true);
fos.write(97);
fos.write(98);
fos.close();
}
}