用Java读取/写入压缩和非压缩文件

这篇文章的主要原因是尝试不重复自己( DRY ),因为通常,我会遇到读写压缩和非压缩文件(主要是JSON和CSV)的递归需求。

首先让我们看看如何读取文本文件。 注意我正在使用(相对较小的)文本文件,因此:

  1. read方法返回一个包含全部内容的String。
  2. 我正在使用BufferedReader逐行读取。
private String readFile(String fileName) {
    StringBuilder sb = new StringBuilder();
    try {
        BufferedReader input = new BufferedReader(new FileReader(new File(fileName)));
        try {
            String line = null;
            while ((line = input.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            input.close();
        }
    } catch (IOException ex) {
        // Handle exception
        return null;
    }

    return sb.toString();
}

注意:做事的方法不只一种。 在条目读取文本文件的最佳方式中 ,您可以找到许多不同的方法来读取文本文件,具体取决于您的JDK版本和文件大小。

类似于将String写入文件:

private void writeFile(String fileName, String value) {
    try {
        FileWriter fw = new FileWriter(fileName);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(value);
        bw.close();
    } catch (IOException ex) {
        // Handle exception
    }
}

要读取/写入带有二进制数据的压缩文件,我们需要使用流和缓冲区。 因此,要读取GZIP压缩文件并获取字符串:

private String readCompressedFile(String fileName) {
    try {
        GZIPInputStream gis = new GZIPInputStream(new FileInputStream(fileName));
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        gis.close();
        return new String(fos.toByteArray());
    } catch (IOException ex) {
        // Handle exception
        return null;
    }
}

并类似地将字符串写入GZip压缩文件:

private void writeCompressedFile(String fileName, String value) {
    try {
        InputStream is = new ByteArrayInputStream(value.getBytes());
        GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream(fileName));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            gzipOS.write(buffer, 0, len);
        }
        gzipOS.close();
        is.close();
    } catch (IOException ex) {
        // Handle exception
    }
}

资源资源

接下来,您可以找到几个适用于各种JDK版本的Java代码的重要链接:

翻译自: https://www.javacodegeeks.com/2015/01/readingwriting-compressed-and-not-compressed-files-in-java.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用JavaZipInputStream类来读取zip压缩文件,然后将数据写入数据库。以下是一个简单的示例代码: ```java import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipFileReader { public static void main(String[] args) { String zipFilePath = "path/to/your/zip/file.zip"; String dbUrl = "jdbc:mysql://localhost:3306/mydatabase"; String dbUsername = "your-username"; String dbPassword = "your-password"; try { // 打开数据库连接 Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword); // 创建插入数据的SQL语句 String insertQuery = "INSERT INTO your_table_name (file_name, file_data) VALUES (?, ?)"; // 创建PreparedStatement对象 PreparedStatement pstmt = conn.prepareStatement(insertQuery); // 创建ZipInputStream对象 ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFilePath)); // 读取zip文件中的每个条目 ZipEntry entry = zipInput.getNextEntry(); while (entry != null) { // 读取条目的文件名和数据 String fileName = entry.getName(); byte[] fileData = new byte[(int) entry.getSize()]; zipInput.read(fileData); // 设置参数并执行插入语句 pstmt.setString(1, fileName); pstmt.setBytes(2, fileData); pstmt.executeUpdate(); // 关闭当前条目,准备读取下一个条目 zipInput.closeEntry(); entry = zipInput.getNextEntry(); } // 关闭ZipInputStream、PreparedStatement和数据库连接 zipInput.close(); pstmt.close(); conn.close(); System.out.println("数据成功写入数据库!"); } catch (IOException | SQLException e) { e.printStackTrace(); } } } ``` 请将代码中的以下内容替换为您自己的信息: - `zipFilePath`:您的zip文件的路径。 - `dbUrl`:您的数据库URL。 - `dbUsername`:您的数据库用户名。 - `dbPassword`:您的数据库密码。 - `your_table_name`:您要插入数据的表名。 这段代码将逐个读取zip文件中的条目,并将每个条目的文件名和数据插入到数据库中。您需要根据自己的需求修改代码以适应您的数据库结构和数据处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值