【Java 输入、输出流】

逃离我推掉我的手 2023-01-13 04:10 284阅读 0赞

Java 输入、输出流(I/O流)

  • 1 File类
    • 1.1 文件的属性
    • 1.2 目录
    • 1.3 文件的创建与删除
    • 1.4 运行可执行文件
  • 2 文件字节输入、输出流
    • 2.1 文件字节输入流
    • 2.2 文件字节输出流
  • 3 文件字符输入、输出流
  • 4 缓冲流

概述:输入、输出流提供一条通道程序,可以使用这条通道读取源中的数据或把数据传送到目的地。把输入流的指向称作源,程序从指向源的输入流中读取源中的数据;而输出流的指向是数据要去的一个目的地,程序通过向输出流中写入数据把数据传送到目的地。

在这里插入图片描述

1 File类

File对象主要用来获取文件本身的一些信息,不涉及对文件的读写操作

创建一个File对象的构造方法有3个,如下:

  1. (1) File(String filename);//filename为文件名
  2. (2) File(String directoryPath,String filename);//directoryPath是文件的路径
  3. (2) File(File dir,String filename);//dir为一个目录

使用File(String filename);创建文件时,该文件位置默认为当前程序所在位置

1.1 文件的属性

File类的下列方法获取文件本身的一些信息。

  1. public String getName()//获取文件的名字。
  2. public boolean canRead()//判断文件是否是可读的。
  3. public boolean canWrite()//判断文件是否可被写入。
  4. public boolean exits()//判断文件是否存在。
  5. public long length()//获取文件的长度(单位是字节)。
  6. public String getAbsolutePath()//获取文件的绝对路径。
  7. public String getParent()//获取文件的父目录。
  8. public boolean isFile()//判断文件是否是一个普通文件,而不是目录。
  9. public boolean isDirectroy()//判断文件是否是一个目录。
  10. public boolean isHidden()//判断文件是否是隐藏文件。
  11. public long lastModified()//获取文件最后修改的时间。

例子1.1(例子中使用上述的一些方法,获取某些文件的信息)

  1. package Example1;
  2. import java.io.File;
  3. public class Example1_1 {
  4. public static void main(String[] args) {
  5. File file = new File("D:\\lifeilin", "lifeilin.txt");//创建文件对象
  6. try {
  7. file.createNewFile();//创建一个新文件
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. System.out.println("文件是否存在:" + file.exists());
  12. System.out.println(file.getName() + "是可读的吗:" + file.canRead());
  13. System.out.println(file.getName() + "的长度:" + file.length());
  14. System.out.println(file.getName() + "的绝对路径:" + file.getAbsolutePath());
  15. }
  16. }

在这里插入图片描述

1.2 目录

(1)创建目录
public boolean mkdir()

(2)列出目录中的文件

  1. public String[] list();用字符串形式返回目录下的全部文件。
  2. public File [] listFiles();用File对象形式返回目录下的全部文件。
  3. public String[] list(FilenameFilter obj)用字符串形式返回目录下的指定类型的所有文件。
  4. public File [] listFiles(FilenameFilter obj)用File对象形式返回目录下的指定类型所有文件。

上述两方法的参数FilenameFilter是一个接口,该接口有一个方法:
public boolean accept(File dir,String name);

例子2(Example1_2.java ,FileAccept.java ),例子2列出当前目录(应用程序所在的目录)下全部java文件的名字)

FileAccept.java

  1. package Example1_2;
  2. import java.io.*;
  3. public class FileAccept implements FilenameFilter {
  4. //FileAccept类实现FilenameFilter接口
  5. private String extendName;
  6. public void setExtendName(String s) {
  7. extendName="."+s;
  8. }
  9. public boolean accept(File dir,String name) {
  10. //重写接口中的方法
  11. return name.endsWith(extendName);
  12. }
  13. }

Example1_2.java

  1. package Example1_2;
  2. import java.io.*;
  3. public class Example1_2 {
  4. public static void main(String[] args) {
  5. File dirFile = new File(".");
  6. FileAccept fileAccept = new FileAccept();
  7. fileAccept.setExtendName("java");
  8. String fileName[] = dirFile.list(fileAccept);
  9. for (String name : fileName) {
  10. System.out.println(name);
  11. }
  12. }
  13. }

1.3 文件的创建与删除

当使用File类创建一个文件对象后,例如
File file=new File(“D:”,“letter.txt”);

如果D:\目录中没有名字为letter.txt文件,文件对象file调用方法
public boolean createNewFile();
文件对象调用方法public boolean delete()可以删除当前文件,
例如:
file.delete();

1.4 运行可执行文件

➢用Runtime类声明一个对象( Runtime类在java.lang包)
Runtime ec;
➢然后使用该类的getRuntime()静态方法创建这个对象:
ec=Runtime.getRuntime();
ec可以调用 exec(String command) 方法打开本地机的可执行
文件或执行一个操作。

下面例子演示打开本地的记事本:

  1. import java.io.*;
  2. public class Example1_4 {
  3. public static void main(String[] args) {
  4. try {
  5. Runtime ce = Runtime.getRuntime();//创建对象
  6. File file = new File("c:/windows", "Notepad.exe");
  7. ce.exec(file.getAbsolutePath());//打开本地记事本
  8. } catch (Exception e) {
  9. System.out.println(e);
  10. }
  11. }
  12. }

2 文件字节输入、输出流

➢java.io包提供了大量的流类.
➢Java把InputStream 抽象类的子类创建的流对象称作字节输入流;OutputStream抽象类的子类创建的流对象称作字节输出流。
➢针对不同的源或目的地。java.io包为程序提供了相应的输入流或输出流。这些输入、输出流绝大部分都是InputStream、OutputStream、Reader或Writer的子类。

2.1 文件字节输入流

使用输入流通常包括4个基本步骤:
(1)设定输入流的源
(2)创建指向源的输入流
(3)让输入流读取源中的数据
(4)关闭输入流。

(1)构造方法:设定输入流源
使用FileInputStream类的下列构造方法创建指向文件的输入流。

  1. FileInputStream(String name);//使用给定的文件名name创建FileInputStream流
  2. FileInputStream(File file);//使用File对象创建FileInputStream流
  3. //参数name和file指定的文件称为输入流的源

FileInpuStream输入流打开一个到达文件的通道(源就是这个文件,输入流指向这个文件)。当创建输入流时,可能会出现错误(也被称为异常)。例如,输入流指向的文件可能不存在。当出现I/O错误,Java 生成一个出错信号,它使用IOException (IO异常)对象来表示这个出错信号。程序必须在try-catch语句中的try块部分创建输入流,在catch (捕获)块部分检测并处理这个异常。例如,为了读取一个名为hello.txt 的文件,建立一个文件输入流in。

  1. try {
  2. FileInputStream in = new FileInputStream("hello.txt");//创建指向文件hello.txt的输入流
  3. } catch (IOException e) {
  4. System.out.println("File read error:" + e);
  5. }

或者:

  1. File f = new File("hello.txt");//指定输入流的源
  2. try {
  3. FileInputStream in = new FileInputStream(f);//创建指向源输入流
  4. } catch (IOException e) {
  5. System.out.println("File read error:" + e);
  6. }

(2)使用输入流读取字节
文件字节流可以调用从父类继承的read方法顺序地读取文件,只要不关闭流,每次调用read方法就顺序地读取文件中的其余内容,直到文件的末尾或文件字节输入流被关闭。

➢int read();读取单个字节的数据,返回字节值(0~255整数) ,如果未读出字节就返回-1。
➢int read(byte b[]);读取b.length个字节到字节数组b中,返回实际读取的字节数。如果到达文件的末尾,则返回-1。
➢int read(byte b[], int off, int len);读取len个字节到字节数组b中,并返回实际读取的字节数目。如果到达文件的末尾,则返回-1,参数off指定从字节数组的某个位置开始存放读取的数据。

(3) 关闭流
输入流都提供了关闭方法close(),尽管程序结束时会自动关闭所有的流,但是当程序使用完流后,显示地关闭任何打开的流仍然是一个良好的习惯,如果没有关闭那些被打开的流,那么就可能不允许另一个程序操作这些所用的资源。

下面例子使用文件字节流读文件内容:

  1. import java.io.*;
  2. public class Example2_1 {
  3. public static void main(String[] args) {
  4. int n = -1;
  5. byte[] a = new byte[100];
  6. try {
  7. File f = new File("D:\\","Example2_1.java");
  8. InputStream in = new FileInputStream(f);
  9. while ((n = in.read(a, 0, 100)) != -1) {
  10. String s = new String(a, 0, n);
  11. System.out.print(s);
  12. }
  13. in.close();
  14. } catch (IOException e) {
  15. System.out.println("File read Error" + e);
  16. }
  17. }
  18. }

2.2 文件字节输出流

➢使用输出流通常包括4个基本步骤:
(1)给出输出流的目的地
(2)创建指向目的地的输出流
(3)让输出流把数据写入到目的地
(4)关闭输出流。

(1)构造方法
使用FileOutputStream类的下列具有刷新功能的构造方法创建指向文件的输出流。

  1. FileOutputStream(String name);
  2. FileOutputStream(File file);
  3. //参数name和file指定的文件称为输出流的目的地

FileOutpuStream输出流开通一个到达文件的通道(目的地就是这个文件,输出流指向这个文件)。需要特别注意的是,如果输出流指向的文件不存在,Java 就会创建该文件,如果指向的文件是已存在的文件,输出流将刷新该文件(使得文件的长度为0)。另外,与创建输入流相同,创建输出流时,可能会出现错误(被称为异常),例如,输出流试图要写入的文件可能不允许操作或有其他受限等原因。所以必须在try-catch语句中的try块部分创建输出流,在catch (捕获)块部分检测并处理这个异常。例如,创建指向名为destin.txt的输出流out。

  1. try {
  2. FileOutputStream out = new FileOutputStream("destin.txt");//创建指向文件destin.txt的输出流
  3. } catch (IOException e) {
  4. System.out.println("File writeerror:" + e);
  5. }

或者:

  1. File f = new File("destin.txt");//指定输出流的源
  2. try {
  3. FileOutputStream out = new FileOutputStream (f);//创建指向源输出流
  4. } catch (IOException e) {
  5. System.out.println("File write:" + e);
  6. }

可以使用FileOutputStream类的下列能选择是否具有刷新功能的构造方法创建指向文件的输出流。

  1. FileOutputStream(String name, boolean append) ;
  2. FileOutputStream(File file, boolean append) ;

当用构造方法创建指向一个文件的输出流时,如果参数append取值true, 输出流不会刷新所指向的文件(假如文件已存在),输出流的write的方法将从文件的末尾开始向文件写入数据,参数append取值false, 输出流将刷新所指向的文件(假如文件已存在)。

(2)使用输出流写字节
输出流的wirie方法以字节单位向目的地写数据。

  1. void write(int n)//向目的地写入单个字节。
  2. void write(byte b[])//向目的地写入一个字节数组。
  3. void write(byte b[],int off,int len)//从字节数组中偏移量off处取len个字节写到目的地。

FileOutputStream流顺序地写文件,只要不关闭流,每次调用write方法就顺序地向目的地写入内容,直到流被关闭。

(3)关闭流
通过调用close()方法,可以保证操作系统把流缓冲区的内容写到它的目的地,即关闭输出流可以把该流所用的缓冲区的内容冲洗掉(通常冲洗到磁盘文件上)。

例子2.2使用文件字节输出流写文件a.txt。
例子2.2首先使用具有刷新功能的构造方法创建指向文件a.txt的输出流、并向a.txt文件写入“新年快乐”,然后再选择使用不刷新文件的构造方法指向a.txt,并向文件写入( 即尾加)“ Happy New Year

  1. import java.io.*;
  2. public class Example2_2 {
  3. public static void main(String[] args) {
  4. byte[] a = "新年快乐".getBytes();
  5. byte[] b = "Happy New Year".getBytes();
  6. File file = new File("D:\\","a.txt"); //输出的目的地
  7. try {
  8. OutputStream out = new FileOutputStream(file); //指向目的地的输出流
  9. System.out.println(file.getName() + "的大小:" + file.length() + "字节");//a.txt的大小:0字节
  10. out.write(a); //向目的地写数据
  11. out.close();
  12. out = new FileOutputStream(file, true); //准备向文件尾加内容
  13. System.out.println(file.getName() + "的大小:" + file.length() + "字节");///a.txt的大小:8字节
  14. out.write(b, 0, b.length);
  15. System.out.println(file.getName() + "的大小:" + file.length() + "字节");///a.txt的大小:8字节
  16. out.close();
  17. } catch (IOException e) {
  18. System.out.println("Error " + e);
  19. }
  20. }
  21. }

在这里插入图片描述

3 文件字符输入、输出流

➢Java把Reader抽象类的子类创建的流对象称作字符输入流;Writer抽象类的子类创建的流对象称作字符输出流。

与FileInputStream. FileOutputStream字节流相对应的是FileReader、FileWriter字符流(文件字符输入、输出流),FileReader 和FileWriter 分别是Reader和Writer的子类,其构造方法分别是:

  1. FileReader(String filename) ;
  2. FileReader(File filename) ;
  3. FileWriter(String filename) ;
  4. FileWriter(File filename) ;
  5. FileWriter(String filename, boolean append) ;
  6. FileWriter(File filename,boolean append) ;

字符输入流和输出流的read和write方法使用字符数组读写数据,即以字符为基本单位处理数据。

➢1. Reader类提供的read方法以字符为单位顺序地读取源中的数据。

  1. int read();
  2. int read(char b[]);
  3. int read(char b[], int off, int len);
  4. void close();

➢2. Writer流 以字符为单位顺序地写文件,每次调用write方法就顺序地向目的地写入内容。Writer类有 如下常用的方法。

  1. void write(int n)//向输出流写入一个字符。
  2. void write(byte b[])//向输出流写入一个字符数组。
  3. void write(byte b[],int off,int length)//从给定字符数组中起始于偏移量off处取len个字符写到输出流。
  4. void close()//关闭输出流。

例子3使用文件字符输入、输出流将文件a.txt的内容尾加到文件b.txt中

  1. import java.io.*;
  2. public class Example3 {
  3. public static void main(String args[]) {
  4. File sourceFile = new File("a.txt"); //读取的文件
  5. File targetFile = new File("b.txt"); //写入的文件
  6. char c[] = new char[19]; //char型数组
  7. try {
  8. Writer out = new FileWriter(targetFile, true); //指向目的地的输出流
  9. Reader in = new FileReader(sourceFile); //指向源的输入流
  10. int n = -1;
  11. while ((n = in.read(c)) != -1) {
  12. out.write(c, 0, n);
  13. }
  14. out.flush();
  15. out.close();
  16. } catch (IOException e) {
  17. System.out.println("Error " + e);
  18. }
  19. }
  20. }

注:对于Writer流,write 方法将数据首先写入到缓冲区,每当缓冲区溢出时,缓冲区的内容被自动写入到目的地,如果关闭流,缓冲区的内容会立刻被写入到目的地。流调用flush0方法可以立刻冲洗当前缓冲区,即将当前缓冲区的内容写入到目的地。

4 缓冲流

➢BufferedReader和BufferedWriter类创建的对象称作缓冲输入、输出流。二者的源和目的地必须是字符输入流和字符输出流。
➢构造方法:

  1. BufferedReader(Reader in);
  2. BufferedWriter(Writer out);

BufferedReader流能够读取文本行,方法是readLine()。通过向BufferedReader 传递一个Reader子类的对象(如FileReader 的实例),来创建一个BufferedReader对象,如:

  1. FileReader inOne = new FileReader("Student. txt") ;
  2. BufferedReader inTwo = BufferedReader(inOne) ;

然后inTwo流调用readLine()方法中读取Student.txt,例如:

  1. String strLine = inTwo. readLine() ;

类似地,可以将BufferedWriter流和FileWriter 流连接在一起, 然后使用BufferedWriter流将数据写到目的地,例如:

  1. FileWriter tofile = new FileWriter("hello.txt") ;
  2. BufferedWriter out = BufferedWriter(tofile) ;

然后out使用BufferedReader类的方法wite(tring s,int off,int len)把字符串s写到hello.txt中,参数off是s开始处的偏移量,len是写入的字符数量。
另外,BufferedWriter 流有-一个独特的向文件写入一 个回行符的方法

newLine() ;

➢BufferedReader和BufferedWriter类读 写文件的方法:

  1. readLine()//读取文本行
  2. write(String s,int of,int len)//把字符串s写到文件中
  3. newLine();// 向文件写入一个回行符

由英语句子构成的文件english. txt (每句占一行):
The arrow missed the target.
They rejected the union demand.
Where does this road go to?

例子4按行读取english. txt,并在该行的后面尾加上该英语句子中含有的单词数目,然后再将该行写入到一个名字为englishCount. txt的文件中

  1. import java.io.*;
  2. import java.util.*;
  3. public class Example10_1 {
  4. public static void main(String[] args) {
  5. File fRead = new File("D:\\","english.txt");
  6. File fWrite = new File("D:\\","englishCount.txt");
  7. try {
  8. Writer out = new FileWriter(fWrite);//指向目的地的输出流
  9. BufferedWriter bufferWrite = new BufferedWriter(out);
  10. Reader in = new FileReader(fRead);//指向源的输入流
  11. BufferedReader bufferRead = new BufferedReader(in);
  12. String str = null;
  13. while ((str = bufferRead.readLine()) != null) {
  14. StringTokenizer fenxi = new StringTokenizer(str);
  15. int count = fenxi.countTokens();
  16. str = str + " 句子中单词个数:" + count;
  17. bufferWrite.write(str);
  18. bufferWrite.newLine();
  19. }
  20. bufferWrite.close();
  21. out.close();
  22. in = new FileReader(fWrite);
  23. bufferRead = new BufferedReader(in);
  24. String s = null;
  25. System.out.println(fWrite.getName() + "内容:");
  26. while ((s = bufferRead.readLine()) != null) {
  27. System.out.println(s);
  28. }
  29. bufferRead.close();
  30. in.close();
  31. } catch (IOException e) {
  32. System.out.println(e.toString());
  33. }
  34. }
  35. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,284人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java输入输出

    相关概念 流的概念: 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象

    相关 Java输入输出

      一、什么是IO   Java中I/O操作主要是指使用Java进行输入,输出操作. Java所有的I/O机制都是基于数据流进行输入输出,这些数据流表示了字符或者字节数据的流

    相关 JAVA 输入/输出

    JAVA 输入/输出流 本次分3个部分详细解说关于Java.io的使用 1、标准设备输入/输出 a) 标准输入/输出类System. System类提供的静态方法中,分别...