0

我使用此代码从 Mysql 将 pdf 文件保存在桌面上,但保存的文件没有扩展名,我如何使用扩展名 pdf 自动保存它,?!!

JFileChooser JFileChooser = new JFileChooser(".");
        Activiter ac = new Activiter();

        int status = JFileChooser.showDialog(null,"Saisir l'emplacement et le nom du fichier cible");

              if(status == JFileChooser.APPROVE_OPTION)
              {
                try
                {
                  ac.chargeIMG(jTable3.getValueAt(rec, 6).toString(),JFileChooser.getSelectedFile().getAbsolutePath());
                }
                catch(Exception ex)
                {
                  JOptionPane.showMessageDialog(null,"Une erreur s'est produite dans le chargement de documents.");
                  ex.printStackTrace();
                }
              }

感谢 ac.chargeIMG 收集的方法 ChargeIMG 的帮助

chargeIMG 是从 MySQL 提供 pdf 文件,代码是

public void chargeIMG(String idpro, String location) throws Exception
    {
        // cnx 

      File monImage = new File(location);
      FileOutputStream ostreamImage = new FileOutputStream(monImage);

      try {

        PreparedStatement ps = conn.prepareStatement("SELECT img FROM projet WHERE idpro=?");

        try
        {
          ps.setString(1,idpro);
          ResultSet rs = ps.executeQuery();

          try
          {
            if(rs.next())
            {
              InputStream istreamImage = rs.getBinaryStream("img");

              byte[] buffer = new byte[1024];
              int length = 0;

              while((length = istreamImage.read(buffer)) != -1)
              {
                ostreamImage.write(buffer, 0, length);
          }
        }
          }
          finally
          {
            rs.close();
          }
        }
        finally
        {
          ps.close();
        }
      }
      finally
      {
        ostreamImage.close();
      }
    }
4

2 回答 2

2

覆盖getSelectedFile()

import java.io.File;
import javax.swing.JFileChooser;

public class MyFileChooser extends JFileChooser
{
    private static final long serialVersionUID = 1L;
    private String extension;

    public MyFileChooser(String currentDirectoryPath, String extension)
    {
        super(currentDirectoryPath);
        this.extension = extension;
    }

    @Override
    public File getSelectedFile()
    {
        File selectedFile = super.getSelectedFile();
        if(selectedFile != null && (getDialogType() == SAVE_DIALOG || getDialogType() == CUSTOM_DIALOG))
        {
            String name = selectedFile.getName();
            if(!name.contains(".")) selectedFile = new File(selectedFile.getParentFile(), name + "." + extension);
        }
        return selectedFile;
    }
}

然后像这样使用它:

JFileChooser chooser = new MyFileChooser(".", "pdf");
于 2013-03-01T18:26:16.177 回答
1

最简单的解决方案,获取路径(File.getPath),检查它是否以预期的扩展名结束,如果不是,则用另一个扩展名存在的文件替换它:new File(path+".pdf");

于 2013-03-01T18:25:16.823 回答