之前一直对JavaIO不太熟悉,在这里做个小结
Java是以流的方式抽象表示不同的输入、输出源。按流的流向分,可以分为输入流和输出流;按操作的数据单元分,可以分为字节流和字符流。
Java的IO流主要有以下四种抽象基类,无法直接创建实例
向文件中写入数据:
写入数据的原理(内存–>硬盘):
Java程序–>JVM–>OS–>OS调用写数据的方法–>把数据写入到文件中
向文件中写入数据一般常用FileOutputStream和FileWriter
FileOutputStream:文件字节输出流,继承了InputStream
使用步骤:
1、创建一个FileOutputStream对象,构造方法中传入写入数据的目的地
2、调用FileOutputStream对象中的方法write,将数据写入到文件中
3、释放资源
FileOutputStream的构造方法
write方法的用法如下:
//使用字节输出流
public static void main(String[] args) throws IOException {
FileOutputStream fos=new FileOutputStream("E:\\java_repository\\123.txt");
String a="你好";
fos.write(a.getBytes());
fos.close();
}
FileWriter:文件字符输出流,继承了Writer
使用步骤:
1、创建FileWriter对象,构造方法中绑定要写入数据的目的地
2、使用FileWriter中的方法write,将数据写入到内存缓冲区中(把字节转换成字符)
3、使用FileWriter中的方法flush,把内存缓冲区的数据刷新到文件中
4、释放资源
write方法:
public static void main(String[] args) throws IOException
{
FileWriter fileWriter=new FileWriter("E:\\java_repository\\a.txt");
fileWriter.write("你好");
fileWriter.flush();
fileWriter.close();
}
flush和close的区别:
flush:刷新缓冲区,流对象可以继续使用
close:刷新缓冲区,再通知系统释放资源,流对象不能再使用了
从文件中读取数据
读取数据的原理(硬盘–>内存):
Java程序–>JVM–>OS–>OS读取数据的方法–>读取文件
从文件中读取数据一般常用FileInputStream和FileReader
FileInputStream:文件字节输入流,继承InputStream
使用步骤:
1、创建FileInputStream对象,构造方法中绑定要读取数据的目的地
2、使用FileWriter中的方法read,读取文件
3、释放资源
构造方法:
read方法:读取到文件的末尾返回-1
//一次读一个字节
private static void input1() throws IOException {
FileInputStream fileInputStream=new FileInputStream("E:\\java_repository\\a.txt");
int len=0;//记录读取到的字节
while((len=fileInputStream.read())!=-1)
System.out.println(len);
fileInputStream.close();
}
//一次读多个字节
private static void input2() throws IOException {
FileInputStream fileInputStream=new FileInputStream("E:\\java_repository\\a.txt");
byte[] b=new byte[100];
int len=fileInputStream.read(b);//从输入流读取一定量的字节,储存在缓存区数组b中
System.out.println(new String(b));
fileInputStream.close();
}
得到了文件中的字节数据,是以二进制码的形式表示的
FileReader:文件字符输入流,继承InputStreamReader和Reader
使用步骤:
1、创建FileReader对象,构造方法中绑定要读取数据的目的地
2、使用FileReader中的方法read,读取文件
3、释放资源
public static void main(String[] args) throws IOException {
FileReader fileReader=new FileReader("E:\\java_repository\\c.txt");
char