2013-03-01 48 views
0

我使用此代碼在桌面上從Mysql保存PDF文件,但文件保存不帶擴展名,如何使用擴展名pdf自動保存文件?使用JFileChooser將名稱命名爲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(); 
       } 
       } 

感謝您的幫助, 梅索德chargerIMG通過ac.chargeIMG

COLLED

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(); 
     } 
    } 
+0

是什麼'ac.chargeIMG()'做什麼? – asgs 2013-03-01 18:23:53

+0

chargeIMG是從MySQL提供的PDF文件,我添加了代碼 – 2013-03-01 18:44:52

回答

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"); 
+0

謝謝,這很好, – 2013-03-01 19:43:42

1

最簡單的辦法,獲得路徑(File.getPath),檢查它是否以預期的擴展名結束,如果不是,則用另一個帶有擴展名的文件替換它:new File(path+".pdf");

相關問題