JavaFX中使用FileChooser获取文件转byte[]存入Blob字段的正确方法
JavaFX 实现选择文件转为byte[]存入数据库的正确方式
实体类定义(存储图片)
@Lob @Column(name = "NOTA_FISCAL", nullable = false, columnDefinition = "mediumblob") public byte[] getNOTA_FISCAL() { return NOTA_FISCAL; } public void setNOTA_FISCAL(byte[] NOTA_FISCAL) { this.NOTA_FISCAL = NOTA_FISCAL; }
原Swing实现逻辑
之前在Swing中通过JFileChooser选择文件并转为byte[]的代码:
private void selecionarNF(ActionEvent event) { JFileChooser fc = new JFileChooser(); int res = fc.showOpenDialog(null); if (res == JFileChooser.APPROVE_OPTION) { File arquivo = fc.getSelectedFile(); System.out.println("Arquivo: " + arquivo + ""); textCaminhoNF.setText(String.valueOf(arquivo)); try { byte[] fotonf = new byte[(int) arquivo.length()]; FileInputStream fileInputfotonf = new FileInputStream(arquivo); fileInputfotonf.read(fotonf); fileInputfotonf.close(); fotoNF = fotonf; } catch (Exception ex) { // System.out.println(ex.printStackTrace().toString()); } } else { JOptionPane.showMessageDialog(null, "Você nao selecionou nenhum arquivo."); } }
JavaFX遇到的问题
JavaFX的FileChooser没有getSelectedFile()方法,原尝试代码报错:
Stage s = new Stage(); FileChooser fc = new FileChooser(); textCaminhoNF.setText(fc.showOpenDialog(s).getAbsolutePath()); File arquivo = fc.getSelectedFile(); // 此行报错,无该方法 if (fc != null) { System.out.println("No is null"); try { byte[] fotonf = new byte[(int) fc.length()]; FileInputStream fileInputfotonf = new FileInputStream(fc); fileInputfotonf.read(fotonf); fileInputfotonf.close(); fotoNF = fotonf; } catch (Exception ex) { // System.out.println(ex.printStackTrace().toString()); } }
正确实现方式
JavaFX的FileChooser.showOpenDialog()直接返回选中的File对象,无需额外调用方法获取。同时建议使用Files.readAllBytes()简化文件读取,或用try-with-resources自动关闭流,避免资源泄漏:
// 若在Controller中,可直接获取当前Stage,无需新建 Stage s = new Stage(); FileChooser fc = new FileChooser(); File arquivo = fc.showOpenDialog(s); // 先判断用户是否选择了文件 if (arquivo != null) { textCaminhoNF.setText(arquivo.getAbsolutePath()); try { // 方式1:Java 7+推荐的简洁读取方式 fotoNF = Files.readAllBytes(arquivo.toPath()); // 方式2:兼容旧版本的流处理(自动关闭资源) /* byte[] fotonf = new byte[(int) arquivo.length()]; try (FileInputStream fileInputfotonf = new FileInputStream(arquivo)) { fileInputfotonf.read(fotonf); fotoNF = fotonf; } */ } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Erro ao ler arquivo: " + ex.getMessage()); } } else { JOptionPane.showMessageDialog(null, "Você não selecionou nenhum arquivo."); }
关键说明
showOpenDialog()返回选中的File,若用户取消选择则返回null,必须先做null判断,避免空指针异常Files.readAllBytes()是Java 7+提供的便捷方法,自动处理流的关闭逻辑- 若需兼容旧版本Java,用try-with-resources包裹
FileInputStream,确保资源自动释放
内容的提问来源于stack exchange,提问作者Homer
相关产品推荐
相关产品推荐

