Save File with Extension

Asked

Viewed 1,079 times

2

I would like to recover a file of the type blob, and to add the extension, without the user having to type this extension when recovering. The way it is, 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 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);

Retrieve 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);
        }

    }
}                     
  • I did not understand very well: you are saving the file in bank, hence want to recover the extension of this file already persisted, is this?

  • Yes, exactly, I have the file in the database, and then the user has the option to make a " download " of this file, however he needs to put the file name and add the extension. And what I wanted was for him to just give up the name, and to automatically add the extension.

  • Includes an answer, see if it helps you :)

1 answer

4


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

Unlike how you’re doing, having a column of the kind blob on the table empresa, maybe a more organized way would be to have a relationship only for the attachments, something like that:

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 persist also the file type information, so you have simply the file extension, without worrying about trying to guess it after.

In case you don’t have the original file, only the binaries, there are some approaches to you recovering it, but there is no guarantee. Some of them are these (as you are creating a file, I am considering approaches starting from a 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
  • make your own routine that checks the binary header. Each extension has its own header, so you could do something that misses these headers.

This Soen question has some interesting answers too: Determining Binary/text file type in Java?.

  • Next, thinking well, your idea of having a table only for the file data would be better, because in my case, it would be important to recover the file with the same name that this had before being sent to the database. Then I could persist the file, name and extension. Correct? Then I just need to see how to do, because I use a Jfilechooser, and in this new way, as I would only choose the location to be saved, because I would take the old name of the table file, or something like that?

  • @Rodrigo save in the table only the name of the file and extension, not the whole directory. To display, you can retrieve the user’s temporary directory and save there. Anything post your question I try to help you

  • @ Bruno César Are there problems in saving the file itself? Beyond the bank space ?

  • @Rodrigo depends expensive, in certain cases not, but in others is not feasible, due to latency for example. It goes a lot of the same necessities, in your case I believe that not.

  • I understand, I will start changing here then with a new table, with name, extension and file. Anything put here, thank you.

  • @ Bruno César, I added more code snippets, Conductive Entity and the Conductive Entity where I launch the violations committed by drivers. Could help with respect to the "new" Attachments Entity and how to persist the attachments in this new way?

  • @Rodrigo, I can, man. Create another issue with the objects you have, explains the persistence scenario, preferably including the DDL of your entities in the bank, then put some alternatives for you there, may be?

  • I created another question.Thank you

  • @Brunocésar I’m testing on Android, I was wondering if it works for Android v2.3.3 (API level 10)

  • Apparently, from API 8 much of the Java API is supported. This should be supported as well, so

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.