java - 从 MySQL 读取文本文件

标签 java mysql file

我正在尝试将文本文件存储在 MySQL 数据库中,并在需要时将其保存到文件中。

为了保存文件,我这样做:

public void saveFile_InDB(File file)
{  
     try {

        String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, new Date().toString());
        statement.setString(2, new Date().toString());

        InputStream inputStream = new FileInputStream(file); 
        statement.setBinaryStream(3, inputStream);

        int row = statement.executeUpdate();
        if (row > 0) {
            System.out.println("File saved sucessfully.");
        }
        conn.close();

    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

并检索并保存文件:

public void retrieveFile_fromDB()
{
     try {

         Statement stmt = (Statement) conn.createStatement();
         ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
         FileOutputStream fos = new FileOutputStream("file.txt");  

         if (res.next()) {

             Blob File = (Blob) res.getBlob("fileName");
             InputStream is = File.getBinaryStream();
             int b = 0;

             while ((b = is.read()) != -1) {
                 fos.write(b);   
             }

             fos.flush();

         }
     } catch (IOException e) {
         e.getMessage (); e.printStackTrace(); 
         System.out.println(e); 
     } catch (SQLException e) {
         e.getMessage (); e.printStackTrace(); 
         System.out.println(e); 
     }
}

存储文件有效,但是当我尝试检索并保存它时,输出文件中没有存储任何内容?

最佳答案

如果你想从 db Mysql 读取文件 在您的代码中更改此部分

  Blob File = (Blob) res.getBlob("fileName");
         InputStream is = File.getBinaryStream();
         int b = 0;

         while ((b = is.read()) != -1) {
             fos.write(b);   
         }

         fos.flush();

使用这段代码读取字节数组

    byte [] bs=res.getBytes("fileName");
    fos.write(bs);

它会起作用 如果你从 db 返回多个文件,你必须声明

 FileOutputStream fos = new FileOutputStream("file.txt");

在 while 循环中更改文件名以避免覆盖

关于java - 从 MySQL 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646856/

相关文章:

java - 使用 Java 的 PostgreSql 复制配置

java - @OneToMany 映射 JPA 中的父 ID 为空

java - 从 HashMap 中读取对象内容

mysql - 每个数据库一张表

java - 在部署 war 中找不到 Spring Boot : external application. 属性

mysql - ERROR 1075 只能有一个自动列,并且必须将其定义为键。帮助我确定如何保留 ReportID 的外键

sql - 慢查询 - 帮助优化

python - 将文本文件导入到python中的二维列表中添加单引号

c - 将文本写入多个c文件中的单个文本文件

file - Flutter:Google Drive:文件列表总是返回 0