0

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

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

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

谢谢。

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

DriverClass、View(GUI)、ReadFile 和 WriteFile。

你可以忽略评论,我只是为自己写的——它们很明显。对于“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();
}
}
4

4 回答 4

1

您的代码中有几个问题:

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

  • sort肯定会IndexOutOfBoundsException为这条线投掷

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

    此行到达最后一个索引时将不起作用,为什么不使用简单Collections.sort(words);

  • 你没有检查用户是否输入了路径,如果没有输入,你将进入NullPointerException你的ReadFile,理想情况下如果找不到文件,即你的扫描仪为空,不要继续。目前您正在显示一条错误消息,但您的代码并没有停在那里,它仍然会尝试读取和排序错误的文件。

于 2012-06-13T06:46:59.833 回答
1

我已经尝试了您的示例并对其进行了调试。我使用 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);
            }
        }
    }
于 2012-06-13T06:56:24.167 回答
1

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

Change the following code in '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();
        }       
    }

and change 'WriteFile.java' to

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

Change 'ReadFile.java' to

public class ReadFile
{
    private ArrayList<String> words;
    private String fileName;
    private Scanner x;

    public ReadFile(String path) throws FileNotFoundException
    {
        fileName = path;
        words = new ArrayList<String>();
        try
        {
            x = new Scanner(new File(fileName));
        } catch (Exception e)
        {
            throw new FileNotFoundException("File Doesn't exist in the place you specified.");
        }
    }


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

        // Now you are done reading and sorting, so close the file.
        x.close();
    }

    .
    .
    .
}
于 2012-06-13T10:18:48.360 回答
0

FileNotFoundException表示未找到该文件。

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

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

于 2012-06-13T10:42:55.537 回答