2017-08-17 93 views
-8

我是相當新到Java和已經看到了一些類似的問題,但還是想問什麼下面的代碼的一部分,是導致以下異常的問題:NullPointerException異常在Java應用程序中

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
at java.io.Writer.write(Unknown Source) 
at FileCopierSwings.actionPerformed(FileCopierSwings.java:158) 
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.setPressed(Unknown Source) 
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) 
at java.awt.Component.processMouseEvent(Unknown Source) 
at javax.swing.JComponent.processMouseEvent(Unknown Source) 
at java.awt.Component.processEvent(Unknown Source) 
at java.awt.Container.processEvent(Unknown Source) 
at java.awt.Component.dispatchEventImpl(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Window.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
at java.awt.EventQueue.access$500(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue.dispatchEvent(Unknown Source) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.run(Unknown Source) 

代碼非常簡單,它打算創建一個窗口,用戶可以瀏覽.txt文件並創建副本。代碼實際上完成了它的工作,但是產生了上面顯示的異常。這裏是完整的代碼:

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
public class FileCopierSwings extends JPanel implements ActionListener{ 
    // Swing components 
    JPanel windowContent; 
    JButton btnBrowse1; 
    JButton btnBrowse2; 
    JButton btnCopy; 
    JLabel lblCopyFrom; 
    JLabel lblCopyTo; 
    JTextField txtFrom; 
    JTextField txtTo; 
    JLabel lblBlank; 
    JFileChooser fileChooser; 
    // I/O variables 
    FileReader fileRead = null; 
    BufferedReader buffRead = null; 
    FileWriter fileWriter = null; 
    BufferedWriter buffWriter = null; 
    File fileOrig, fileCopy; 

    // Constructor 
    FileCopierSwings(){ 
     windowContent = new JPanel(); 
     // set grid layout 
     GridLayout gl = new GridLayout(3,3,2,2); 
     windowContent.setLayout(gl); 
     // initialize components 
     btnBrowse1 = new JButton("Browse"); 
     btnBrowse2 = new JButton("Browse"); 
     btnCopy = new JButton("Copy"); 
     lblCopyFrom = new JLabel("Copy From:"); 
     lblCopyTo = new JLabel("Copy To:"); 
     txtFrom = new JTextField(10); 
     txtTo = new JTextField(10); 
     lblBlank = new JLabel(" "); 

     // add to panel 
     windowContent.add(lblCopyFrom); 
     windowContent.add(txtFrom); 
     windowContent.add(btnBrowse1); 

     windowContent.add(lblCopyTo); 
     windowContent.add(txtTo); 
     windowContent.add(btnBrowse2); 

     windowContent.add(lblBlank); 
     windowContent.add(btnCopy); 

     // register action listeners 
     btnBrowse1.addActionListener(this); 
     btnBrowse2.addActionListener(this); 
     btnCopy.addActionListener(this); 

     // create frame 
     JFrame frame = new JFrame("File copier"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setContentPane(windowContent); 
     frame.pack(); 
     frame.setVisible(true); 

    }// end of constructor 

    public static void main(String[] args) { 

     @SuppressWarnings("unused") 
     FileCopierSwings fileCopier = new FileCopierSwings(); 

    }// end of main 

    @Override 
    public void actionPerformed(ActionEvent e) { 

     // select the file to copy 
     if (e.getSource() == btnBrowse1) { 

      fileChooser = new JFileChooser(); 

      int returnVal = fileChooser.showOpenDialog(FileCopierSwings.this); 
      //fileChooser.showOpenDialog(FileCopierSwings.this); 

      if (returnVal == JFileChooser.APPROVE_OPTION) { 
       fileOrig = fileChooser.getSelectedFile();// file selected 
       txtFrom.setText(fileOrig.getPath());// display file path on label 
      }else { 
       txtFrom.setText("None selected"); 
      } 
     } 
     // select file of destination 
     if (e.getSource() == btnBrowse2) { 

      fileChooser = new JFileChooser(); 

      int returnVal = fileChooser.showDialog(FileCopierSwings.this, "Copy"); 
      //fileChooser.showOpenDialog(FileCopierSwings.this); 

      if (returnVal == JFileChooser.APPROVE_OPTION) { 
       fileCopy = fileChooser.getSelectedFile(); 
       txtTo.setText(fileCopy.getPath()); 
       // check of file exists, it not then creates a file 
       if (!fileCopy.exists()) { 
        try { 
         fileCopy.createNewFile(); 
         System.out.println("new file "+ fileCopy.getName() + " created"); 
        } catch (IOException e1) { 
         System.out.println("Error creating file"); 
         e1.printStackTrace(); 
        } 
        // if file exists display message that indicates that the file will be Overwritten 
       }else{ 
        System.out.println("Overwriting file "+ fileCopy.getName()); 
        javax.swing.JOptionPane.showConfirmDialog(null, 
          "file already exist and will be overwritten", "alert!", 
          javax.swing.JOptionPane.PLAIN_MESSAGE); 
       } 
      }else { 
       txtTo.setText("None selected"); 
      } 
     } 
     // when the user click the copy button 
     if (e.getSource() == btnCopy) { 
      // open file and create reader buffer 
      try {    
       fileRead = new FileReader(fileOrig.getPath()); 
       buffRead = new BufferedReader(fileRead); 

       // create writer buffer 
       fileWriter = new FileWriter(fileCopy.getPath()); 
       buffWriter = new BufferedWriter(fileWriter); 

       while (true) { 
        // copy the content of the file 
        String line = buffRead.readLine(); 

        // write the line in the destination file 
        buffWriter.write(line); 
        buffWriter.newLine(); 

        // check for end of file to exit 
        if (line == null) break; 
       } 

      }catch (IOException ex){ 
       System.out.println("Can't read the file"); 
      }finally { 
       // flush and close all 
       try { 
        buffRead.close(); 
        fileRead.close(); 
        buffWriter.flush(); 
        buffWriter.close(); 
        fileWriter.close(); 
        System.out.println("closing operation completed"); 
       }catch (IOException ex) { 
        ex.printStackTrace(); 
        System.out.println("Something is wrong closing..."); 
       } 
      }   
     }  
    }// end of actionPerformed 
} 

請讓我知道哪裏可能是問題,謝謝,最好的問候。

+2

在這個問題太多的代碼。你需要減少你的問題[mcve]。很多時候,你會發現你的問題在這樣做的過程中已經解決了。 – shmosel

+0

你知道你可以用更簡單的方式複製文件:'Files.copy(fileOrig.toPath(),fileCopy.toPath());'就是這樣。 –

回答

0

您需要檢查line == null之前您是否嘗試寫入它。通常情況下,這看起來像這樣:

String line; 
while ((line = buffRead.readLine()) != null) { 
    // write the line in the destination file 
    buffWriter.write(line); 
    buffWriter.newLine(); 
} 
+0

你的答案解決了這個問題。謝謝您的回覆。 – JRomero

+0

@JRomero如果解決了您的問題,請點擊支票[接受答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – shmosel

相關問題