欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Java-I/O流

Java-I/O流

2025/3/16 8:26:59 来源:https://blog.csdn.net/qq_46209845/article/details/145946732  浏览:    关键词:Java-I/O流

一、文件

在这里插入图片描述

1.1 初识文件

文件是保存数据的地方,文件在程序中是以流的形式来操作的。

  • 流:数据在数据源(文件)和程序(内存)之间经历的路径。
  • 输入流:数据从数据源(文件)到程序(内存)的路径。
  • 输出流:数据从程序(内存)到数据源(文件)的路径。

1.2文件基本操作

1.2.1文件的创建

三种文件创建的形式
在这里插入图片描述

public class FileCreate {//new File(String path+fileName).createNewFile@Testpublic void create01(){String path = "f:\\重头来过\\创建文件目录\\create01.txt";try {File file = new File(path);file.createNewFile();} catch (IOException e) {throw new RuntimeException(e);}}//new File(File parentFile,String fileName).createNewFile@Testpublic void create02(){//创建文件目录File parentFile = new File("f:\\重头来过\\创建文件目录");String fileName = "create02.txt";File file = new File(parentFile, fileName);try {file.createNewFile();} catch (IOException e) {throw new RuntimeException(e);}}//new file(String parentPath,String fileName).createNewFile@Testpublic void create03(){String parentPath = "f:\\重头来过\\创建文件目录";String fileName = "create03.txt";File file = new File(parentPath, fileName);try {file.createNewFile();} catch (IOException e) {throw new RuntimeException(e);}}
}

1.2.2获取文件信息

  1. 对象.getName():获取文件名
  2. 对象.getAbsolutePath():获取文件绝对路径
  3. 对象.getParent():获取文件父目录
  4. 对象.length():文件大小(字节)
  5. 对象.exists():查看文件是否存在
  6. 对象.isFile():对象是否为文件
  7. 对象.isDirectory():对象是否是目录

1.2.3常用文件操作

Java中目录被认为指一种特殊的文件,创建目录操作时 对象.mkdir() 创建多级目录 对象.mkdirs,要删除目录 对象.delete() 时必须保证目标是空目录,若目录内有文件(文件夹也不行),则删除失败。

public class Directory01 {//判断f:\重头来过\javaio\create01.txt是否存在,存在就删除@Testpublic void test01(){String filePath = "f:\\重头来过\\javaio\\create01.txt";File file = new File(filePath);if(file.exists()){if(file.delete()){System.out.println("删除成功");}else{System.out.println("删除失败");}}else {System.out.println("文件不存在");}}//判断f:\\javaio是否存在,存在就删除,否则提示不存在//如果目录内有文件则不能删除目录,只能删除空目录@Testpublic void test02(){String path = "f:\\重头来过\\javaio";File file = new File(path);if(file.exists()){if(file.delete()) {System.out.println(path + "删除成功");} else {System.out.println("删除失败");}}else {System.out.println("该目录不存在");}}//判断f:\\重头来过\\javaio\\a\\b\\c是否在,不存在创建目录//多级目录得用mkdirs,单级目录用mkdir@Testpublic void test03(){String path = "f:\\重头来过\\javaio\\a\\\\b\\c";File file = new File(path);if(file.exists()){System.out.println("文件目录已存在");} else {if (file.mkdirs()){System.out.println(path +  "创建成功");}else {System.out.println(path + "创建失败");}}}
}

二、I/O流(Input/Output流)

在这里插入图片描述

1.io流基础知识

  • Io流原理

在这里插入图片描述

在这里插入图片描述

  • io流的分类

在这里插入图片描述

  • Java中的io流

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

2. 字节流

2.1InputStream 字节输入流

在这里插入图片描述

FileInputStream(字节输入流实现类)

在这里插入图片描述

public class StuInputStream {@Testpublic void test01() throws Exception {String path = "f:\\重头来过\\javaio\\hello.txt";
//        File file = new File(path);
//        FileInputStream fileInputStream = new FileInputStream(file);FileInputStream fileInputStream = new FileInputStream(path);//设置字符集读取中文InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");int read = 0;//一个字节一个字节的读while ((read = inputStreamReader.read())!= -1) {System.out.print((char) read);}inputStreamReader.close();fileInputStream.close();}@Testpublic void test02() throws Exception {String path = "f:\\重头来过\\javaio\\hello.txt";FileInputStream fileInputStream = new FileInputStream(path);byte[] bytes = new byte[1024];int len = 0;//一次读完(假设接受的bytes能装下,装不下还是要while)//如果读取正常返回读取到的字节数len = fileInputStream.read(bytes);System.out.println(new String(bytes,0,len));fileInputStream.close();}
}

2.2 OutputStream 字节输出流

FileOutPutStream 字节输出流实现类

在这里插入图片描述

  1. 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
public class StuOutputStream {@Testpublic void test01() throws Exception {String path = "f:\\重头来过\\javaio\\a.txt";FileOutputStream fileOutputStream = new FileOutputStream(path);String s = "hello world 666";//两种写法都可以fileOutputStream.write(s.getBytes(),0,s.length());//fileOutputStream.write(s.getBytes(),0,s.getBytes().length);fileOutputStream.close();}
}

需要注意的是这种

FileOutputStream fileOutputStream = new FileOutputStream(path)

方式实例化的输出字节流会覆盖源文件的内容,如果想要追加到源文件的末尾,应该使用这种

在这里插入图片描述

FileOutputStream fileOutputStream = new FileOutputStream(path,true)

重新实现一遍

public class StuOutputStream {@Testpublic void test02() throws Exception {String path = "f:\\重头来过\\javaio\\a.txt";FileOutputStream fileOutputStream = new FileOutputStream(path,true);String s = "hello world 666";//两种写法都可以fileOutputStream.write(s.getBytes(),0,s.length());fileOutputStream.close();}
}

在代码执行之前记事本中的内容:

在这里插入图片描述

执行2次代码之后:

在这里插入图片描述

小练习之文件拷贝

把e:\tu.png复制到f:\重头来过\javaio\tu.png

public class FileCopy {public static void main(String[] args) throws Exception {FileInputStream fileInputStream = new FileInputStream("e:\\tu.png");FileOutputStream fileOutputStream = new FileOutputStream("f:\\重头来过\\javaio\\tu.png");byte[] bytes = new byte[1024];int len = 0;while ((len = fileInputStream.read(bytes)) != -1) {fileOutputStream.write(bytes, 0, len);}fileInputStream.close();fileOutputStream.close();}
}

3.字符流

3.1 FileReader字符输入流

在这里插入图片描述

public class readStory {@Testpublic void test() throws Exception {FileReader reader = new FileReader("f:\\重头来过\\javaio\\story.txt");char[] buf = new char[1024];int len = 0;while ((len = reader.read(buf)) != -1){System.out.println(new String(buf, 0, len));}reader.close();}
}

3.2 FileWrier 字符输出流

在这里插入图片描述

//用writer和reader配合复制文件
public class NewCopy {public static void main(String[] args) throws IOException {FileReader reader = new FileReader("f:\\重头来过\\javaio\\story.txt");FileWriter writer = new FileWriter("f:\\重头来过\\storyCopy.txt");int len = 0;char[] chars = new char[8];while ((len = reader.read(chars)) != -1) {writer.write(chars, 0, len);writer.flush();}reader.close();writer.close();}
}

代码中加不加 flush() 都能复制成功的原因

在你给出的代码中,加不加 flush() 都能复制成功,这是因为在调用 close() 方法时,Java 会自动调用
flush() 方法,将缓冲区中的数据写入到目标设备。具体来说,当你调用 writer.close() 时,FileWriter
会自动将缓冲区中的数据写入到文件中,然后关闭文件流。因此,即使你没有显式调用 flush() 方法,数据也会被正确写入到目标文件中。

对于flush:
在 Java 的 I/O 操作中,为了提高效率,通常会使用缓冲区。缓冲区是内存中的一块区域,用于临时存储要写入或读取的数据。当你调用 write() 方法时,数据并不是立即被写入到目标设备(如文件),而是先被存储在缓冲区中。当缓冲区满了或者调用 close() 方法时,缓冲区中的数据才会被写入到目标设备。
flush() 方法的作用就是强制将缓冲区中尚未写入目标设备的数据立即写入。

4.节点流和处理流

在这里插入图片描述

在这里插入图片描述

4.1 BufferedReader

//演示通过BufferedReader 读入文件
public class StuBufferedReader {public static void main(String[] args) throws IOException {String path = "f:\\重头来过\\javaio\\story.txt";BufferedReader bufferedReader = new BufferedReader(new FileReader(path));String line = null;while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}bufferedReader.close();}
}

4.2 BufferedWriter

public class StuBufferedWriter {public static void main(String[] args) throws IOException {String path = "f:\\重头来过\\javaio\\hahaha.txt";BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(path, true));bufferedWriter.write("你好1");bufferedWriter.newLine(); //根据系统换行bufferedWriter.write("你好2");bufferedWriter.newLine();bufferedWriter.write("你好3");bufferedWriter.newLine();bufferedWriter.close();}
}

在这里插入图片描述

4.3 ObjectStream对象流

在这里插入图片描述

4.4 ObjectOutputStream

public class ObjectOutputStream_ {public static void main(String[] args) throws IOException {String filePath = "f:\\重头来过\\javaio\\data.dat";ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));oos.writeInt(100);oos.writeObject(new Dog("haha",2));oos.close();System.out.println("数据保存完毕(序列化形式)...");}
}
//Dog类
public class Dog implements Serializable {public String name;public int age;public Dog(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Dog{" +"name='" + name + '\'' +", age=" + age +'}';}
}

4.4 ObjectInputStream

public class ObjectInputStream_ {public static void main(String[] args) throws IOException, ClassNotFoundException {String filePath = "f:\\重头来过\\javaio\\data.dat";ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));System.out.println(ois.readInt());System.out.println((Dog)ois.readObject());}
}

在这里插入图片描述

4.5标准输入流和标准输出流

在这里插入图片描述

4.6转换流 InputStreamReader & OutputStreamWriter

在这里插入图片描述

public class StuInputStream {@Testpublic void test01() throws Exception {String path = "f:\\重头来过\\javaio\\hello.txt";
//        File file = new File(path);
//        FileInputStream fileInputStream = new FileInputStream(file);FileInputStream fileInputStream = new FileInputStream(path);//设置字符集读取中文InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");int read = 0;//一个字节一个字节的读while ((read = inputStreamReader.read())!= -1) {System.out.print((char) read);}inputStreamReader.close();fileInputStream.close();}
}

在这里插入图片描述

4.7 PrintStream

三、Properties类

在这里插入图片描述

对于这个配置文件:在这里插入图片描述

我们用已经学过的方法来读入到程序中是这样的:

public class Tradition {public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new FileReader("F:\\重头来过\\代码\\stu_io\\src\\mysql.properties"));String s =null;while ((s = br.readLine()) != null){String[] split = s.split("=");System.out.println(split[0] + "的值是" + split[1]);}br.close();}

在这里插入图片描述

关于properties

在这里插入图片描述
在这里插入图片描述

//读
public class Test {public static void main(String[] args) throws IOException {//1.创建Properties 对象Properties properties = new Properties();//2.加载指定配置文件properties.load(new FileReader("F:\\重头来过\\代码\\stu_io\\src\\mysql.properties"));//3.把k-v显示控制台properties.list(System.out);//4.根据key 获取对应的valueString user = properties.getProperty("user");String password = properties.getProperty("pwd");System.out.println("用户名" + user);System.out.println("密码" + password);}
}
//写
public class Test2 {public static void main(String[] args) throws IOException {//使用Properties 类来创建配置文件,修改配置文件内容Properties properties = new Properties();//创建//如果没有这个key就是创建,有就xiu'gaproperties.setProperty("charset", "utf8");properties.setProperty("user", "汤姆");properties.setProperty("password", "123456");//将k-v存储文件中即可properties.store(new FileOutputStream("src\\mysql2.properties"),"哈哈");System.out.println("配置文件保存成功");}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词