Save file with extension

2

I would like to recover a file of type blob , and add the extension, without the user having to type this extension at the time of recovery. As it stands, I'm saving and also recovering, but recovering without the extension.

I have the button attach, then the save button.

To recover the file (save in the desired folder) I have the recover button.

Attach button:

private void jBAnexarArquivoActionPerformed(java.awt.event.ActionEvent evt) {                                                
    caminho = null;
    JFileChooser file = new JFileChooser();
    file.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int i = file.showSaveDialog(null);
    if (i == 1) {
        JtextFieldLocalArquivo.setText("");
    } else {
        File arquivo = file.getSelectedFile();
        JtextFieldLocalArquivo.setText(arquivo.getPath());
        caminho = arquivo.getPath();
    }
}

Save button:

String path = caminho;
FileInputStream input = null;
File theFile = new File(path);
input = new FileInputStream(theFile);
byte[] bytes = IOUtils.toByteArray(input);
empresa.setAnexo(bytes);

Recover button:

private void jBRecuperarArquivoActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    Connection con = new SQLConnection().getConnection();
    Statement myStmt = null;
    ResultSet myRs = null;
    InputStream input = null;
    FileOutputStream output = null;
    try {
        myStmt = con.createStatement();
        String sql = "select anexo from empresa where idEmpresa = '" + empresaIdField.getText() + "'";
        myRs = myStmt.executeQuery(sql);
        JFileChooser fileChooser = new JFileChooser();
        int returnValue = fileChooser.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            String path = selectedFile.getAbsolutePath();

            output = new FileOutputStream(selectedFile);
            if (myRs.next()) {
                input = myRs.getBinaryStream("anexo");
                byte[] buffer = new byte[1024];
                while (input.read(buffer) > 0) {
                    output.write(buffer);
                }

            }
        }

    } catch (Exception exc) {
        exc.printStackTrace();
    } finally {
        if (input != null) {

            try {
                input.close();
            } catch (IOException ex) {
                Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}                     
    
asked by anonymous 20.09.2015 / 21:17

1 answer

4

The simplest approach to use, since you have the original file, is to also save the file extension or mime type .

Unlike what you're doing, having a blob column in the empresa table, maybe a more organized way would be to have a list only for attachments, something like this:

CREATE TABLE anexos (
    id int(11) not null,
    content blob not null,
    extension varchar(10) not null,
    empresa_id int(11) not null,
    constraint foreign key (empresa_id) references empresa (id)
)

As you can see, you would also persist the file type information, so you simply have to extend it, without bothering to guess it later.

If you do not have the original file, just the binaries, there are some approaches to recovering this, but there is no guarantee. Some of these are these (as you are creating a file, I am considering approaches that start from File / Path ):

final File file = new File("F:/Java-8-Features.pdf");
final Path path = file.toPath();
final String mime = Files.probeContentType(path);

// apache tika
final MimeTypes types = MimeTypes.getDefaultMimeTypes();
final MimeType mimeType = types.forName(mime);
final String extension = mimeType.getExtension();
// faça o que for preciso com a extensão
final InputStream is = rs.getBinaryStream("anexo");
final String mime = URLConnection.guessContentTypeFromStream(is);

// apache tika
final MimeTypes types = MimeTypes.getDefaultMimeTypes();
final MimeType mimeType = types.forName(mime);
final String extension = mimeType.getExtension();
// faça o que for preciso com a extensão
  • Do your own routine that checks the binary header. Each extension has its own header, so I could do something that maps these headers.

This SOen question has some interesting answers as well: Determining binary / text file type in Java? .

    
20.09.2015 / 22:42