Java IO流

File

在Java中,File类是java.io包的一部分,它用于文件和目录路径名的抽象表示形式。File类可以用于创建、删除文件,检查文件是否存在,获取文件大小,以及进行其他与文件或目录相关的操作。

1.创建文件或目录

createNewFile(): 创建文件,如果文件已存在则不执行任何操作。

delete():删除文件或目录(目录必须为空)。

示例1:创建和删除文件
import java.io.File;  
import java.io.IOException;  
  
public class FileCreateDeleteExample {  
    public static void main(String[] args) {  
        // 创建文件  
        File file = new File("example.txt");  
        try {  
            if (file.createNewFile()) {  
                System.out.println("文件创建成功: " + file.getName());  
            } else {  
                System.out.println("文件已存在: " + file.getName());  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 删除文件  
        if (file.delete()) {  
            System.out.println("文件删除成功: " + file.getName());  
        } else {  
            System.out.println("文件删除失败");
        }  
    }  
}

// 创建一个指向名为"newfile.txt"的File对象  
File file = new File("newfile.txt");  
  
// 尝试创建一个新的空文件,如果文件不存在则创建并返回true,否则返回false  
if (file.createNewFile()) {  
    System.out.println("File created successfully.");  
} else {  
    System.out.println("File already exists.");  
}  
  
// 删除file指向的文件或目录,如果删除成功则返回true,否则返回false  
if (file.delete()) {  
    System.out.println("File deleted successfully.");  
} else {  
    System.out.println("Failed to delete file.");  
}

2. 文件和目录的判断和获取

  • exists() : 判断文件或目录是否存在。
  • isDirectory() : 判断是否为目录。
  • isFile() : 判断是否为文件。
  • getName() : 获取文件或目录的名称。
  • getPath() : 获取文件或目录的路径。
  • getAbsolutePath() : 获取文件或目录的绝对路径。
  • getParent() : 获取父目录的路径。
  • listFiles() : 返回目录下的所有文件和子目录的 File 对象数组。
示例1:文件目录的判断和获取
// 创建一个指向名为"mydir"的目录的File对象  
File directory = new File("mydir");  
  
// 判断目录是否存在并且是一个目录  
if (directory.exists() && directory.isDirectory()) {  
    System.out.println("Directory exists.");  
  
    // 获取目录下的所有文件和子目录,返回File数组  
    File[] files = directory.listFiles();  
    if (files != null) {  
        // 遍历File数组,并打印每个文件或目录的名称  
        for (File file : files) {  
            System.out.println(file.getName());  
        }  
    }  
} else {  
    System.out.println("Directory does not exist.");  
}

3. 文件和目录的操作

  • mkdir() : 创建一个目录。
  • mkdirs() : 创建多级目录。
  • renameTo(File dest) : 重命名文件或目录。
示例1:文件和目录操作
// 创建一个指向名为"newdir"的目录的File对象  
File dir = new File("newdir");  
  
// 尝试创建目录,如果成功则返回true  
if (dir.mkdir()) {  
    System.out.println("Directory created successfully.");  
} else {  
    System.out.println("Failed to create directory.");  
}  
  
// 创建一个指向多级目录"nested/dirs"的File对象  
File newDir = new File("nested/dirs");  
  
// 尝试创建多级目录,如果成功则返回true  
if (newDir.mkdirs()) {  
    System.out.println("Nested directories created successfully.");  
} else {  
    System.out.println("Failed to create nested directories.");  
}  
  
// 创建两个File对象,分别指向旧文件名和新文件名  
File oldFile = new File("oldname.txt");  
File newFile = new File("newname.txt");  
  
// 尝试将oldFile重命名为newFile,如果成功则返回true  
if (oldFile.renameTo(newFile)) {  
    System.out.println("File renamed successfully.");  
} else {  
    System.out.println("Failed to rename file.");  
}

4. 文件和目录的属性和信息

  • length() : 获取文件的大小(以字节为单位)。
  • lastModified() : 获取文件最后修改的时间。
示例1:文件和目录的属性和信息
// 创建一个指向文件"example.txt"的File对象  
File file = new File("example.txt");  
  
// 判断file是否是一个文件  
if (file.isFile()) {  
    // 获取文件的大小(以字节为单位)  
    long size = file.length();  
    System.out.println("File size: " + size + " bytes");  
  
    // 获取文件最后修改的时间  
    long lastModified = file.lastModified();  
    System.out.println("Last modified: " + new Date(lastModified));  
} else {  
    System.out.println("Not a file.");  
}

5. 路径处理

  • File(String parent, string child) : 通过父路径和子路径创建 File 对象。
  • separator : 用于获取系统相关的路径分隔符。
示例1:路径处理
// 创建一个指向"parent"目录的File对象  
File parentDir = new File("parent");  
  
// 通过父目录和子文件名创建一个新的File对象,指向"parent/child.txt"  
File childFile = new File(parentDir, "child.txt");  
  
// 打印childFile的路径  
System.out.println(childFile.getPath()); 
// 输出类似于 "parent\child.txt" 或 "parent/child.txt",取决于系统  
  
// 获取系统相关的路径分隔符  
String separator = File.separator;  
  
// 打印路径分隔符  
System.out.println("Path separator: " + separator); 
// 输出系统相关的路径分隔符,如"\"或"/"

Path

path接口是Java NI0 2(也称为Java 7引入的新I/0 API)的一部分,它代表一个文件系统路径。这个接口提供了大量方法来操作和查询路径,使得处理文件和目录变得更加简单和灵活。

功能:

  1. 表示文件或目录的路径 :Path 对象可以用来表示文件系统中的某个位置,可以是文件或目录。
  2. 跨平台性 :  Path 使用系统相关的路径分隔符,从而实现了跨平台的路径处理。
  3. 操作丰富 :  Path 接口提供了很多方法,比如获取父路径、文件名、文件扩展名,解析路径,检查路径是否存在等。
  4. 与 Files 类配合 : Path 经常与 Files 类一起使用,以执行文件或目录的I/O操作,如读取、写入、复制、移动等。
1.创建path对象

使用Paths类的get静态方法创建Path对象。

// 创建一个指向文件的Path对象  
Path path = Paths.get("path/to/file.txt");
2.解析路径

使用resolve或resolveSibling方法来解析相对于当前路径的新路径。

// 解析相对于当前路径的新路径  
Path resolvedPath = path.resolve("subdir/anotherfile.txt");
3.获取路径组件

使用getParent、getFileName、getRoot等方法获取路径的不同组件。

// 获取路径的父目录  
Path parentPath = path.getParent();  
// 获取路径的文件名  
Path fileName = path.getFileName();
4.检查路径属性

使用isAbsolute、isDirectory、isFile等方法检查路径的属性。

// 检查路径是否是绝对路径  
boolean isAbsolute = path.isAbsolute();  
// 检查路径是否指向一个目录  
boolean isDirectory = Files.isDirectory(path);
5.规范化路径

使用normalize方法消除路径中的冗余分隔符、父目录引用("..")和当前目录引用(".")。

// 规范化路径  
Path normalizedPath = path.normalize();
6.获取相对路径

使用relativize方法获取从当前路径到另一路径的相对路径。

// 获取相对路径  
Path basePath = Paths.get("/home/user");  
Path targetPath = Paths.get("/home/user/documents/file.txt");  
Path relativePath = basePath.relativize(targetPath);
7.转换为URI或File对象

使用toUri或toFile方法将Path对象转换为URI或File对象。

// 转换为URI  
URI uri = path.toUri();  
// 转换为File对象  
File file = path.toFile();
8.文件操作

使用Files类的静态方法执行文件或目录的I/O操作。

// 检查文件是否存在  
boolean exists = Files.exists(path);  
// 读取文件内容  
try {  
    byte[] fileContent = Files.readAllBytes(path);  
    String content = new String(fileContent);  
    System.out.println(content);  
} catch (IOException e) {  
    e.printStackTrace();  
}  
// 创建目录  
try {  
    Files.createDirectories(dirPath);  
    System.out.println("Directory created successfully.");  
} catch (IOException e) {  
    e.printStackTrace();  
}  
// 删除文件或目录  
try {  
    Files.deleteIfExists(pathToDelete);  
    System.out.println("File/Directory deleted successfully.");  
} catch (IOException e) {  
    e.printStackTrace();  
}

在Java中,流(Stream)是一个非常重要的概念,主要用于处理输入/输出操作。流可以被视为数据的通道,它连接了数据的源和目标,使得数据可以从一个地方传输到另一个地方。Java的流可以分为字节流和字符流,它们分别用于处理二进制数据和文本数据。

字节流和字符流

字节流(Byte Streams):

InputStream:所有字节输入流的超类。

OutputStream:所有字节输出流的超类。

字节流主要用于处理原始二进制数据,如图片、音频、视频等文件。

字符流(Character Streams):

Reader:所有字符输入流的超类。

Writer:所有字符输出流的超类。

字符流主要用于处理文本数据,它按照字符编码进行数据的读写。

字节流:

//创建字节输入流:
InputStream inputStream = new FileInputStream("path/to/file");
//创建字节输出流:
OutputStream outputStream = new FileOutputStream("path/to/file");
//读取数据:
byte[] buffer = new byte[1024];  
int bytesRead = inputStream.read(buffer);
//写入数据:
String data = "Hello, World!";  
byte[] bytes = data.getBytes();  
outputStream.write(bytes);

字符流:

//创建字符输入流:
Reader reader = new FileReader("path/to/file.txt");
//创建字符输出流:
Writer writer = new FileWriter("path/to/file.txt");
//读取数据:
char[] buffer = new char[1024];  
int charsRead = reader.read(buffer);
//写入数据:
String text = "你好,世界!";  
writer.write(text);
缓冲流

为了提高读写效率,Java提供了缓冲流,它们分别是BufferedInputStream /BufferedOutputStream和BufferedReader / BufferedWriter。缓冲流会将数据先写入一个内部缓冲区,等缓冲区满或调用flush()方法时,再将数据一次性写入目标。

//创建缓冲字节流:
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("path/to/file"));  
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("path/to/file"));
//创建缓冲字符流:
BufferedReader bufferedReader = new BufferedReader(new FileReader("path/to/file.txt"));  
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("path/to/file.txt"));
字节流示例:复制文件
import java.io.*;  
  
public class FileCopyExample {  
    public static void main(String[] args) {  
        File sourceFile = new File("source.txt"); // 源文件  
        File destinationFile = new File("destination.txt"); // 目标文件  
          
        try (InputStream in = new FileInputStream(sourceFile); // 创建输入流,读取源文件  
             OutputStream out = new FileOutputStream(destinationFile)) { 
// 创建输出流,写入目标文件  
              
            byte[] buffer = new byte[1024]; // 创建缓冲区,用于临时存储读取的数据  
            int bytesRead; // 存储每次从输入流中读取的字节数  
              
            // 循环读取源文件中的数据,直到没有数据可读  
            while ((bytesRead = in.read(buffer)) != -1) {  
                out.write(buffer, 0, bytesRead); 
// 将读取到的数据写入目标文件  
            }  
              
            // 使用try-with-resources语句可以确保在try代码块执行完毕后,流会自动关闭  
        } catch (IOException e) {  
            e.printStackTrace(); // 如果发生I/O异常,则打印异常堆栈  
        }  
    }  
}
字符流示例:读取并打印文本文件内容
import java.io.*;  
  
public class FileReaderExample {  
    public static void main(String[] args) {  
        File file = new File("text.txt"); // 文本文件  
          
        try (Reader reader = new FileReader(file)) { // 创建字符输入流,用于读取文本文件  
            int c; // 存储每次从输入流中读取的字符  
              
            // 循环读取文本文件中的字符,直到没有字符可读  
            while ((c = reader.read()) != -1) {  
                System.out.print((char) c); // 将读取到的字符转换为字符串并打印  
            }  
              
            // 使用try-with-resources语句可以确保在try代码块执行完毕后,流会自动关闭  
        } catch (IOException e) {  
            e.printStackTrace(); // 如果发生I/O异常,则打印异常堆栈  
        }  
    }  
}

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值