扩展.csv文件数据JAVA时出现问题

时间:2019-07-15 10:12:38

标签: java exception try-catch

我在Java AddressBook上遇到问题,我试图编辑和更新存储在.csv文件中的一行数据中的值

我尝试遍历代码并检查逻辑错误,但似乎找不到引发try catch异常的原因。确实确实可以做到这一点,却无法弄清停止运行的原因

    private class ammendActionListener implements ActionListener {

        public ammendActionListener() {
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
           String filePath = "Personal.csv";
           String editTerm = id.getText();
           String newID = id.getText();
           String newFName = fn.getText();
           String newLName = ln.getText();
           String newAddr = addr.getText(); 
           String newAddr2 = addr2.getText();
           String newPost = post.getText();
           String newCont = cont.getText();

           editRecord(filePath, editTerm, newID, newFName, newLName, newAddr, newAddr2, newPost, newCont);
        }
    }
    private Scanner x; 
    public void editRecord(String filePath, String editTerm, String newID, String newFName, String newLName, String newAddr, String newAddr2, String newPost, String newCont){
        String tempFile = "temp.csv"; 
        File oldFile = new File(filePath);
        File newFile = new File(tempFile);
        String ID = ""; String first = ""; String last = ""; String addr =""; String addr2=""; String post = ""; String cont = ""; 
        try{
            FileWriter fw = new FileWriter(tempFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            x = new Scanner(new File(filePath));
            x.useDelimiter("[,\n]");

            while(x.hasNext()){
                ID = x.next();
                first = x.next();
                last = x.next();
                addr = x.next();
                addr2 = x.next();
                post = x.next();
                cont = x.next();

                if(ID.equals(editTerm)){
                    pw.println(newID+","+newFName+","+newLName+","+newAddr+","+newAddr2+","+newPost+","+newCont);
                }else{
                    pw.println(ID+","+first+","+last+","+addr+","+addr2+","+post+","+cont);
                }
            }
            x.close();
            pw.flush();
            pw.close();
            oldFile.delete();
            File dump = new File(filePath);
            newFile.renameTo(dump);

        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "ERROR");
        }

    }

}

我希望文件通过标识要重写的ID列并重命名temp.csv文件并删除带有更新的行的原始Presonal.csv来修改适当的数据。正确执行


成功建立

总时间:36.814 s 结束于:2019-07-15T11:07:47 + 01:00

最终记忆:13M / 47M

更新错误

java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at com.mycompany.ppaddressbook.ammContact.editRecord(ammContact.java:174)
at
  com.mycompany.ppaddressbook.ammContact$ammendActionListener.actionPerformed(ammContact.java:154)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6632)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6397)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5008)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4840)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2762)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4840)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

1 个答案:

答案 0 :(得分:0)

我想问题是File#renameTo()。根据Javadoc的说法,此方法在很大程度上依赖于平台库。

  

此方法的行为的许多方面本质上都依赖于平台:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,并且如果包含以下内容的文件可能无法成功:目标抽象路径名已存在。应该始终检查返回值,以确保重命名操作成功。

您的代码可在我的环境中使用,但是要使其节省使用在任何平台上,您应该使用NIO-Library(新IO)。这是一个快速代码,可以完成您打算做的事情。请注意,您不需要刷新或关闭读取器/写入器,因为try-with-resources会为您完成这些操作。

public class Test {
    public static void main(String[] args) {
        Test test = new Test();
        test.editRecord("C:/temp/test.csv", "2", "2", "foobar", "baz");
    }

    public void editRecord(String filePath, String editTerm, String newID, String newFName, String newLName){
        String tempFile = "temp.csv"; 
        Path oldPath = Paths.get(filePath);
        Path newPath = Paths.get(tempFile);

        try(BufferedReader reader = Files.newBufferedReader(oldPath); BufferedWriter writer = Files.newBufferedWriter(newPath)) {
            String read;
            while( (read = reader.readLine()) != null ) {
                String[] line = read.split(",");
                if(line[0].equals(editTerm)) {
                    line[0] = newID;
                    line[1] = newFName;
                    line[2] = newLName;
                }

                writer.append(String.join(",", line));
                writer.newLine();
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

        try {
            Files.move(newPath, oldPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

    }

}

编辑:

考虑将Files.createTempFile("temp", ".csv");用于临时文件。

由于抛出IOException的可能性很大,因此最好在throws上添加editRecord(...)。您可以捕获异常并将其显示在调用方上。