首页 > 编程语言 >Java文件与IO流

Java文件与IO流

时间:2023-05-20 10:44:38浏览次数:41  
标签:文件 Java String java IOException IO new import public

首先我们要清楚什么是流,正如其名,很形象,流就是像水一样的东西,具有方向性,在java中
,流大概就是类
接下来,我们要对输入输出流有一个基本认识,什么是输入输出流呢?
输入输出明显需要一个参照,而这个参照就是主存。
清楚了上面的概念,我们接着看下去吧。
1.png

文件

文件的创建

文件创建共有三种方式
1、

File file = new File(文件的路径);
file.createNewFile();

2、

File file = new File(文件的父目录, 文件名);

3、

File file = new File(文件的父目录, 文件的子目录);

package file;

import org.junit.jupiter.api.Test;
import java.awt.*;
import java.io.File;
import java.io.IOException;

public class FileCreate {
    public static void main(String[] args) {

    }
    //@Test
    public void create01() throws IOException {
        String filePath = "E:\\new1.txt";
        File file = new File(filePath);
        file.createNewFile();
        System.out.println("文件创建成功");
    }
    //@Test
    public void create02() throws IOException {
        File file1 = new File("E:\\");
        String fileName = "new2.txt";
        File file = new File(file1, fileName);
        file.createNewFile();
        System.out.println("文件创建成功2");
    }
    @Test 
    public void create03()
    {
        String FilePath = "E:\\";
        String FileName = "new3.txt";
        File file = new File(FilePath, FileName);
        try {
            file.createNewFile();
            System.out.println("文件创建成功3");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

文件信息的获取

package file;

import java.io.File;

public class FileInformation {
    public static void main(String[] args) {
        FileInformation fileInformation = new FileInformation();
        fileInformation.info();
    }
    public void info()
    {
        File file = new File("E:\\new1.txt");
        System.out.println("文件名=" + file.getName());
        System.out.println("文件的句=绝对路径" + file.getAbsoluteFile());
        System.out.println("文件的父目录" + file.getParentFile());
        System.out.println("文件的大小" + file.length());
        System.out.println("文件是否存在" + file.exists());
        System.out.println("是否是一个文件" + file.isFile());
        System.out.println("是否是一个目录" + file.isDirectory());
    }
}

2.png

目录文件的创建和删除

删除

package file;

import com.sun.javafx.image.BytePixelSetter;
import org.junit.jupiter.api.Test;

import java.io.File;

public class Directory_ {
    public static void main(String[] args) {

    }
    @Test
    public void f1()
    {
        String filePath = "E:\\new1.txt";
        File file = new File(filePath);
        if(file.exists())
        {
            if(file.delete()) System.out.println("删除成功");
            else System.out.println("删除成功");
        }else{
            System.out.println("该文件不存在");
        }
    }
}

目录创建

mkdir创建一级目录、mkdirs创建多级目录

@Test
    public void f3()
    {
        String filePath = "D:\\demo\\a\\b\\c";
        File file = new File(filePath);
        if(file.exists())
        {
            System.out.println("目录存在");
        }else {
            if(file.mkdirs()) System.out.println("该目录创建成功");
            else System.out.println("该目录创建失败");
        }
    }

IO流

流的分类

1、按照数据单位不同分为字节流(操作二进制的文件)和字符流(一个字符占多少个字节是不确定的这和编码有点关系,操作文本文件
2、按流向单位不同分为输入流和输出流。
3、按流的角色分:节点流和处理流(这里角色改没有引入下面会介绍)

InputStream和OutStream、Reader、Writer是四个个抽象类,其他类均是实现的这四个Abstract类,均以他们作为后缀名

1.png
2.png

输入流

字节输入流

package inputstream;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStream_ {
    public static void main(String[] args) {
    }
    //@Test
    public void readFile01() throws IOException {
        String filePath = "D:\\hello.txt";
        FileInputStream fileInputStream = null;
        int readdata = 0;
        try {
            fileInputStream = new FileInputStream(filePath);
           //返回-1表示文件读完了
            while((readdata = fileInputStream.read()) != -1){
                System.out.print((char) readdata);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭文件流
            fileInputStream.close();
        }
    }
    @Test
    public void readFile02() throws IOException {
        String filePath = "D:\\hello.txt";
        byte[] buf = new byte[8];
        FileInputStream fileInputStream = null;
        int readlen = 0;
        try {
            fileInputStream = new FileInputStream(filePath);
            //返回-1表示文件读完了
            while((readlen = fileInputStream.read(buf)) != -1){
                System.out.print(new String(buf, 0, readlen));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭文件流
            fileInputStream.close();
        }
    }
}

字节输出流

package outputstream_;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStream01 {
    public static void main(String[] args) {

    }
    @Test
    public void writeFile() throws IOException {
        String filePath = "D:\\a.txt";
        FileOutputStream fileOutputStream = null;
        try {
            String str = "Hello World";
            fileOutputStream = new FileOutputStream(filePath);
           //写一个字符
            // fileOutputStream.write('C');
            //写一个字符串
             fileOutputStream.write(str.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            fileOutputStream.close();
        }
    }
}
        fileOutputStream = new FileOutputStream(filePath);是覆盖
        fileOutputStream = new FileOutputStream(filePath, true);是追加到源文件后

应用

package outputstream_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) throws IOException {
        //文件拷贝,将D:\\1.png拷贝到C:\\
        //1、创建文件的输入流,将文件读入程序
        //2、创建文件的输出流,将程序中的内容写入文件
        String filePath = "D:\\1.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        byte[] buf = new byte[1024];
        int readlen = 0;
        fileInputStream = new FileInputStream(filePath);
        fileOutputStream = new FileOutputStream("E:\\1.jpg");
        while((readlen = fileInputStream.read()) != -1)
        {
            //读取后写入文件,边读边写
            fileOutputStream.write(buf, 0, readlen);
        }
        fileOutputStream.close();
        fileInputStream.close();
    }
}

FileReader

package filereader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\a.txt";
        FileReader fileReader = null;
        int data = 0;
        try {
            fileReader = new FileReader(filePath);
            while((data = fileReader.read()) != -1)
            {
                System.out.print((char) data);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            fileReader.close();
        }
    }
}

用字符数组来读

package filereader;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args){
    }
    @Test
    public void readFile01() throws IOException {
        String filePath = "D:\\a.txt";
        int readlen = 0;
        FileReader fileReader = null;
        char [] buf = new char[8];
        try {
            fileReader = new FileReader(filePath);
            while((readlen = fileReader.read(buf)) != -1)
            {
                System.out.print(new String(buf, 0, readlen));
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            fileReader.close();
        }
    }

}

FileWriter

写入数据之后一定要关流或者刷新数据才能被写入

package filewrite;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriter_ {
    public static void main(String[] args) {
        String path = "D:\\a.txt";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path, true);
            fileWriter.write("aaaa");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

节点流和处理流

处理流是连接在已存在的流之上为程序提供更强大的读写功能,包装流更加形象
9.png

BufferedReader & BufferedWriter

package BufferedReader_;

import javax.swing.text.Style;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReader_ {
    public static void main(String[] args) throws IOException {
        String path = "D:\\a.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        String line;
        try {
            //bufferedReader.readLine();按行读取,当读取到空时,表示读取结束
            while((line = bufferedReader.readLine()) != null) System.out.println(line);;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            bufferedReader.close();
        }
    }
}
package bufferedreader;

import java.io.*;

public class BufferedReader_ {
    public static void main(String[] args) throws IOException {
        String path = "D:\\a.txt";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(path, true));

        try {
            bufferedWriter.write("阿杜吃饱饱");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            bufferedWriter.flush();
        }

    }
}

视频、图片等是二进制文件用字节流更方便

对象流

使用细节
1、读写顺序要一致
2、要求实现序列化或反序列化对象,需要实现Serializable
3、序列化默认是将所有属性都序列化,但是static和transient不序列化
4、序列化里面的属性也要是现实Serializable接口

标准输入输出流

转换流

转换流应用的情况:
因为字符流不能指定编码格式,而字节流可以指定编码格式,可以先按字节流读入,再用转换流转化,这样就不会乱码了

标签:文件,Java,String,java,IOException,IO,new,import,public
From: https://www.cnblogs.com/cxy8/p/17410854.html

相关文章

  • 使用ln命令在Linux系统中创建连接文件
    在Linux中ln命令用来为文件创建连接,连接类型分为硬连接(HardLink)和符号连接(SymbolicLink)两种,默认的连接类型是硬连接。如果要创建符号连接必须使用"-s"选项。关于软硬连接解释硬连接硬连接是指通过索引节点来进行连接。在Linux的文件系统中,保存在磁盘分区中的文件不管是......
  • 一种基于token 和 Permission 的权限管理中间件示例
    1.先上封装后的使用效果[Permission(Key="/User/AddUser")][HttpPost]publicResultAddUser([FromBody]SaUseruser){//Dosth.thrownewNotImplementedException();}[Authorize]......
  • ChatGPT 推出 iOS 应用,支持语音输入,使用体验如何?
    最近,OpenAI宣布推出官方iOS应用,允许用户随时随地访问其高人气AI聊天机器人,此举也打破了近几个月内苹果AppStore上充斥似是而非的山寨服务的窘境。该应用程序是ChatGPT的首个官方移动应用程序。ChatGPT软件程序在去年推出后迅速获得了超过1亿用户,这也让技术行业火速......
  • Connections could not be acquired from the underlying database!
    报错内容:五月19,20239:02:42上午org.apache.catalina.core.StandardWrapperValveinvoke严重:在路径为的上下文中,Servlet[springmvc]的Servlet.service()引发了具有根本原因的异常Requestprocessingfailed;nestedexceptionisorg.springframework.transaction.CannotCreat......
  • flutter系列之:使用AnimationController来控制动画效果
    目录简介构建一个要动画的widget让图像动起来总结简介之前我们提到了flutter提供了比较简单好用的AnimatedContainer和SlideTransition来进行一些简单的动画效果,但是要完全实现自定义的复杂的动画效果,还是要使用AnimationController。今天我们来尝试使用AnimationController来实现......
  • TheForces Round #13 (Boombastic-Forces) G. Permutation Removal
    感觉好久没有写过这样单独一篇题目的博客了的说昨天上大物课的时候ztc问了我这道题,然后我口胡了下感觉还挺有趣的不过其它题目就没啥时间看了,正巧最近在练DP专题,就顺手记录一下吧这题的数据范围和问题一眼区间DP的形式,直接设\(f_{l,r}\)表示区间\([l,r]\)的答案刚开始naive地......
  • 1094 The Largest Generation
    题目:Afamilyhierarchyisusuallypresentedbyapedigreetreewhereallthenodesonthesamelevelbelongtothesamegeneration.Yourtaskistofindthegenerationwiththelargestpopulation.InputSpecification:Eachinputfilecontainsonetestcas......
  • Family of Solution Sets
      欢迎投歌词!评论告诉我歌曲链接和词就好啦~大概四五天一更?SolutionSet-“卷起击碎定论的漩涡”\(\to\)《夏虫》SolutionSet-“让季节停止哽咽”\(\to\)《凉雨》SolutionSet-“也许我们早已经共鸣在那约定之地”\(\to\)《视星等4.44》SolutionSet-......
  • nginx 默认配置文件
    #usernobody;worker_processes1;#error_loglogs/error.log;#error_loglogs/error.lognotice;#error_loglogs/error.loginfo;#pidlogs/nginx.pid;events{worker_connections1024;}http{includemime.types;defau......
  • 2023-05-19:汽车从起点出发驶向目的地,该目的地位于出发位置东面 target 英里处。 沿途
    2023-05-19:汽车从起点出发驶向目的地,该目的地位于出发位置东面target英里处。沿途有加油站,每个station[i]代表一个加油站,它位于出发位置东面station[i][0]英里处,并且有station[i][1]升汽油。假设汽车油箱的容量是无限的,其中最初有startFuel升燃料。它每行驶1英里......