【java文件流处理】
  TEZNKK3IfmPf 2024年04月19日 37 0

Java文件流处理是指使用Java编程语言中的输入流和输出流来读取和写入文件。文件流处理可以用于读取和写入文本文件、二进制文件、字符文件等。

Java中常用的文件流处理类有以下几种:

  1. FileInputStream和FileOutputStream:用于读取和写入字节流,可以用于处理任意类型的文件。

示例代码:

// 读取文件
try (FileInputStream fis = new FileInputStream("input.txt")) {
    int data;
    while ((data = fis.read()) != -1) {
        System.out.print((char) data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 写入文件
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
    String data = "Hello, World!";
    fos.write(data.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}
  1. FileReader和FileWriter:用于读取和写入字符流,适合处理文本文件。

示例代码:

// 读取文件
try (FileReader fr = new FileReader("input.txt")) {
    int data;
    while ((data = fr.read()) != -1) {
        System.out.print((char) data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 写入文件
try (FileWriter fw = new FileWriter("output.txt")) {
    String data = "Hello, World!";
    fw.write(data);
} catch (IOException e) {
    e.printStackTrace();
}
  1. BufferedReader和BufferedWriter:用于读取和写入缓冲字符流,可以提高读写效率。

示例代码:

// 读取文件
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 写入文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    String data = "Hello, World!";
    bw.write(data);
} catch (IOException e) {
    e.printStackTrace();
}

通过Java文件流处理,可以方便地读取和写入文件的内容,实现文件的读写操作。

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ReadFileFromPath {

    public static void main(String[] args) {
        String filePath = "C:/path/to/file.txt"; // specify the file path here

        File file = new File(filePath);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                Files.probeContentType(file.toPath()), Files.readAllBytes(file.toPath()));

        try {
            byte[] fileContent = multipartFile.getBytes();
            // Process the file content as required
            System.out.println(new String(fileContent));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年04月19日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   19天前   43   0   0 java
  TEZNKK3IfmPf   2024年05月31日   54   0   0 java
TEZNKK3IfmPf