一、IO流
1、字节流
1>字节输出流(OutputStream)
FileOutputStream
构造方法:
- FileOutputStream(String name):创建一个具有指定名称的文件中写入数据的输出文件流。
- FileOutputStream(File file):创建一个具有指定为file对象表示的文件中写入数据的输出文件流。
字节输出流的使用步骤:
- 创建一个FileOutputStream对象,构造方法中,传递写入数据的目的地。
- 调用FileOutStream的对象中的方法write,把数据写入文件中。
- 释放资源。
public class IO {
public static void main(String[] args) throws IOException {
FileOutputStream FOS= new FileOutputStream("C:\\Users\\fanjingchen\\Desktop\\1.text");
FOS.write(98);
FOS.close();
}
}
一次写多个字节的方法:
- public void write(byte[] b) :将b.length字节从指定的数组写入此输出流。
public class IO {
public static void main(String[] args) throws IOException {
FileOutputStream FOS= new FileOutputStream("C:\\Users\\fanjingchen\\Desktop\\2.text");
FOS.write(49);
FOS.write(48);
FOS.write(48);
FOS.close();
}
}
- 如果写的第一个字节是正数,那么会查询ASCLL码。
public class IO {
public static void main(String[] args) throws IOException {
FileOutputStream FOS= new FileOutputStream("C:\\Users\\fanjingchen\\Desktop\\3.text");
byte[] bytes={
65,66,67,68,69};
FOS.write(bytes);
FOS.close();
}
}
运行结果:
ABCDE
- 如果如果写的第一个字节是负数,那第一个字节和第二个字节,两个字节组成一个中文显示,查询系统默认码表(GBK)。
public class IO {
public static void main(String[] args) throws IOException {
FileOutputStream FOS= new FileOutputStream("C:\\Users\\fanjingchen\\Desktop\\3.text");
byte[] bytes={
-65,-66,-67,68,69};
FOS.write(bytes);
FOS.close();
}
}
运行结果:
烤紻E
- public void write(byte[] b,int off,int len):从指定的字节数组中写入len字节,从偏移量off开始输出到此输出流。
public class IO {
public static void main(String[] args) throws IOException {
FileOutputStream FOS= new FileOutputStream("C:\\Users\\fanjingchen\\Desktop\\3.text");
byte[] bytes={
65,66,67,68,69};
FOS.write(bytes,1,2);
FOS.close();
}
}
运行结果:
BC
- 写入字符的方法可以使用String中的方法把字符串,转换为字节数组。byte[] bytes=“范璟琛”.getBytes();
byte[] bytes="范璟琛".getBytes();
System.out.println(Arrays.toString(bytes));
运行结果:
[-24, -116, -125, -25, -110, -97, -25, -112, -101]
数据的追加写和续写
- FileOutputStream(String name , boolean append):创建一个具有指定名称的文件中写入数据的输出文件流。
- FileOutputStream(File file , boolean append):创建一个具有指定为file对象表示的文件中写入数据的输出文件流。
- 参数:boolean:追加开关。
- true:创建对象不会覆盖原文件,继续在文件的末尾追加数据。
- f