Java-IO流初识

2022/3/8 1:15:08

本文主要是介绍Java-IO流初识,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.File类的使用

java.io.File类:

  • 文件和文件目录路径的抽象表示形式,与平台无关
  • File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
  • 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
  • File对象可以作为参数传递给流的构造器
 1 class Test3 {
 2     public static void main(String[] args) throws IOException {
 3         File file1 = new File("hello.txt");
 4         File file3 = new File("D:\\整理\\Exer_code\\src\\www\\hello.txt");
 5         //getParent():获取上层文件目录路径
 6         //在"D:\\整理\\Exer_code\\src\\www"路径下,hellotest.txt为子路径创建File对象(目标文件)
 7         File destfile = new File(file3.getParent(), "hellotest.txt");
 8         //创建文件"hellotest.txt",若文件存在则不创建并返回false
 9         boolean newFile = destfile.createNewFile();
10         if (newFile) {
11             //创建成功,输出语句
12             System.out.println("Created Successfully");
13         }
14     }
15 }

 

2.节点流(文件流)的应用

class Testcopy{
    public static void main(String[] args) {
        FileReader fw = null;
        FileWriter dr = null;
        try {
            //创建文件对象,指明读入文件和写入文件
            File srcfile = new File("D:\\整理\\Exer_code\\src\\www\\hello.txt");
            File destfile = new File("D:\\整理\\Exer_code\\src\\www\\hello1.txt");
            //创建文件输入流和输出流
            fw = new FileReader(srcfile);
            dr = new FileWriter(destfile);
            //数据的读入和写出操作
            char[] cbuf = new char[5];
            int len;
            while ((len = fw.read(cbuf)) != -1){
                    dr.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                //关闭资源
                if(fw != null);
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                if(dr != null);
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

四个步骤

1.建立一个流对象,将已存在的一个文件加载进流。  FileReader fr = new FileReader(new File(“Test.txt”));

2.创建一个临时存放数据的数组。 char[] ch = new char[1024];

3.调用流对象的读取方法将流中的数据读入到数组中。 fr.read(ch);

4. 关闭资源。 fr.close();

 



这篇关于Java-IO流初识的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程