【问题标题】:File Sorter - fileNotFoundException文件分类器 - fileNotFoundException
【发布时间】:2012-06-13 06:17:13
【问题描述】:

我正在尝试创建一个读取File 的程序,将内容(单词)保存在ArrayList 中,对ArrayList 进行排序,然后将排序后的内容写入 ArrayListFile

我不知道为什么,它一直给我FileNotFoundExceptionNullPointerException(两者都在发生,有点奇怪)...

这是我的代码,如果有人可以提供帮助,那就太好了。

谢谢。

顺便说一下,代码包含四个类:

DriverClass、View(GUI)、ReadFile 和 WriteFile。

您可以忽略 cmets,我只是为自己写的 - 它们非常明显。对于“field.getText();”假设用户输入C:\Users\Corecase\Desktop\test.txt 我试过做C:\\Users\\Corecase\\Desktop\\test.txt) 但这也不起作用。

再次感谢!

public class DriverClass 
{
    public static void main(String[] args)
    {
        View open= new View();
    }
}

//查看

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class View implements ActionListener
{
private JFrame frame = new JFrame("File Sorter");
private JPanel mainPane = new JPanel();
private JPanel textPane = new JPanel();
private JPanel buttonPane = new JPanel();
private JButton sortButton = new JButton("Sort");
private JLabel label = new JLabel("Enter file path: ");
public JTextField field = new JTextField(25);

private Font f = new Font("Trebuchet MS", Font.PLAIN, 20);


public View()
{
    frame.setSize(500,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(mainPane);

    mainPane.setLayout(new GridLayout(2,1));
    mainPane.setBackground(Color.gray);

    mainPane.add(textPane);
    mainPane.add(buttonPane);

    textPane.setLayout(new GridLayout(2,1));
    textPane.add(label);
    textPane.add(field);
    buttonPane.add(sortButton);
    field.setFont(f);
    sortButton.setFont(f);
    label.setFont(f);

    sortButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == sortButton)
    {
        ReadFile r = new ReadFile(field.getText());
        WriteFile w = new WriteFile(field.getText());

        r.openFile();
        r.readAndSortFile();
        r.closeFile();

        w.openFile();
        w.writeFile(r.getList());
        w.closeFile();
    }
}
}

//读取文件

import java.io.*;
import java.util.*;

public class ReadFile extends View
{
private ArrayList<String> words = new ArrayList<String>();
private String fileName = new String();
private Scanner x;

public ReadFile(String address)
{
    fileName = address;
}
public void openFile()
{
    try
    {
        x = new Scanner(new File(fileName));
    }
    catch(Exception e)
    {
        field.setText("Could not read file.");
    }
}

public void readAndSortFile()
{
    while(x.hasNext())
        words.add(x.next());

    sort();
}

public void closeFile()
{
    x.close();
}

public ArrayList<String> sort()
{
    String temp = "";

    for(int index = 0; index < words.size(); index++)
    {
        for(int inner = 0; inner < words.size(); inner++)
        {
            if((words.get(inner)).compareTo(words.get(inner+1)) > 0)
            {
                temp = words.get(inner);
                words.set(inner, words.get(inner + 1));
                words.set(inner + 1, temp);
            }
        }
    }
    return words;
}

public ArrayList<String> getList()
{
    return words;
}
}

//写入文件

import java.io.*;
import java.util.*;
import java.lang.*;

public class WriteFile extends View
{
private Formatter x;
private String fileName = new String();

public WriteFile(String address)
{
    fileName = address;
}

public void openFile()
{
    try
    {
        x = new Formatter(fileName);
    }
    catch(Exception e)
    {
        field.setText("Could not write to file.");
    }
}

public void writeFile(ArrayList<String> myWords)
{
    for(int index = 0; index < myWords.size(); index++)
        x.format("%s", myWords.get(index), "\n");//%s means string - in this case ONE string
}

public void closeFile()
{
    x.close();
}
}

【问题讨论】:

  • 我看不出你提到的两个输入之间的区别。另外,请尝试使用正斜杠 ('/') 而不是反斜杠。
  • 反斜杠在 Windows 上是可以的。并且转义反斜杠仅对字符串文字是必需的,控制台(或大多数类型的输入)中的用户不必转义它们。
  • 你能把问题减少到代码中存在错误的地方,而不是给出整个程序吗? Stacktraces 通常指向异常的行。
  • 你说你得到了异常但你没有显示堆栈跟踪。
  • 等待堆栈跟踪。建议:您正在手动对数组列表进行排序。您可以使用 String 类中可用的 Collections.sort() 方法和比较器,这将减少您的代码。

标签: java user-interface nullpointerexception java.util.scanner filenotfoundexception


【解决方案1】:

您的代码中有几个问题。您正在扩展 View 以获取 textField 'field' 的引用!这不是要走的路。您应该使用异常处理来完成这个简单的任务。您也不能同时读取和写入文件!所以你需要在这里分开职责。当你读完文件后,关闭它,然后用你想使用的任何作家再次打开它。最后说明:您可以使用 FileChooser 来获取路径,这样您就无需检查有效输入!如果您想硬着头皮强制用户手动输入路径,则必须添加转义字符“/”,在您的情况下,有效路径为 C:\\Users\\Corecase\\Desktop\\test.txt

在'View.java'中修改如下代码

    if (e.getSource() == sortButton)
    {
        ReadFile r;
        try
        {
            r = new ReadFile(field.getText());
            r.readAndSortFile();

            WriteFile w = new WriteFile(field.getText());
            w.writeFile(r.getList());

        } 
        catch (FileNotFoundException e1)
        {
            field.setText(e1.getMessage());
            e1.printStackTrace();
        }       
    }

并将“WriteFile.java”更改为

public class WriteFile
{
    private Formatter x;
    private String fileName;

    public WriteFile(String address) throws FileNotFoundException
    {
        fileName = address;
        try
        {
            x = new Formatter(fileName);
        } catch (Exception e)
        {
            throw new FileNotFoundException("Could not write to file.");
        }
    }

    public void writeFile(ArrayList<String> myWords)
    {
        for (int index = 0; index < myWords.size(); index++)
            x.format("%s%s", myWords.get(index), System.lineSeparator());

        // now you are done writing so close the file.

        x.close();
    }
}

将“ReadFile.java”更改为

公共类 ReadFile
{
    私有 ArrayList 单词;
    私有字符串文件名;
    私人扫描仪 x;

    公共读取文件(字符串路径)抛出 FileNotFoundException
    {
        文件名 = 路径;
        words = new ArrayList();
        尝试
        {
            x = 新扫描仪(新文件(文件名));
        } 捕捉(异常 e)
        {
            throw new FileNotFoundException("文件在你指定的地方不存在。");
        }
    }


    公共无效 readAndSortFile()
    {
        而 (x.hasNext())
            words.add(x.next());
        Collections.sort(单词);

        // 现在你已经完成了读取和排序,所以关闭文件。
        x.close();
    }

    .
    .
    .
}

【讨论】:

    【解决方案2】:

    您的代码中有几个问题:

    • ReadFileWriteFile 正在扩展 View,根据构造函数,您将打开多个 JFrame 实例,因为您使框架在构造函数 frame.setVisible(true);、@987654326 中可见@ 和WriteFile 只需要引用应该更新的JTextField,只需将其作为参数传递即可。

    • 你的sort 肯定会为这条线抛出IndexOutOfBoundsException

      if ((words.get(inner)).compareTo(words.get(inner + 1)) > 0) {

      这条线到达最后一个索引就不行了,为什么不用简单的Collections.sort(words);

    • 1234563不要进一步。目前您正在显示一条错误消息,但您的代码并没有停在那里,它仍然会尝试读取和排序错误的文件。

    【讨论】:

      【解决方案3】:

      我已经尝试了您的示例并对其进行了调试。我使用 c:\\dir\\file.text 作为 GUI 的参数并且文件被正确读取,所以它不存在你的问题。我得到的异常来自这段代码:

          for (int index = 0; index < words.size(); index++) {
              for (int inner = 0; inner < words.size(); inner++) {
                  if ((words.get(inner)).compareTo(words.get(inner + 1)) > 0) {
                      temp = words.get(inner);
                      words.set(inner, words.get(inner + 1));
                      words.set(inner + 1, temp);
                  }
              }
          }
      

      【讨论】:

        【解决方案4】:

        FileNotFoundException 表示找不到文件。

        NullPointerException 表示您试图取消引用空指针。

        如果这不能回答您的问题,我不知道是什么。 StackOverflow 不是调试服务。

        【讨论】:

        • 你说得对; StackOverflow 不是调试服务 - 它是人们互相帮助理解/解决问题的服务。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 2015-02-20
        • 2015-12-05
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多