1

所以我的问题是标题如何。下面是我的代码片段。我知道我应该使用 try/catch,但在我的 catch 中,我不知道该怎么做。我收到一个错误 / HERE / 说 BufferedReader 不能接收 InputStream。我想继续使用 BufferedReader,那么是否有任何其他类可以在我的新 BufferedReader 中实例化,以便我的编译器满意?任何帮助将不胜感激,谢谢!

    //reads in 'dictionary' file
    BufferedReader bReader;
    try
    {
        bReader = new BufferedReader
                (new FileReader("unsortedWords.txt"));
    }
    catch (FileNotFoundException e)
    {
        System.out.print("Enter name of dictionary file: ");
        bReader = new BufferedReader
                (new FileReader(System.in)); /*HERE*/
    }
4

2 回答 2

3

也许是这样:

File file = new File("unsortedWords.txt");
if(file.exists())
{
 // do something
}
else
{
 // prompt for file
 // if command line you can use Scanner or an InputStreamReader
 // if GUI you can use a File Chooser.
}

如果您不确定如何执行命令行或 GUI 操作,请询问我,我将发布其余代码。

[编辑]:我看到你正在做命令行,所以你可以试试这个:

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();

[编辑]:示例类(是的,它的设计很糟糕,但我写得很快):

import java.io.*;

public class Temp
{

    public static void main(String[] args) throws IOException
    {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        System.out.println("Hello World!");
        String temp = br.readLine();
        System.out.println("Your line : \"" + temp + "\"");
    }
}

[编辑]:这是我制作的课程,应该适合您。

import java.io.*;

public class Temp
{

    public static void main(String[] args) throws IOException
    {
        String fileName = "RandomFileThatDoesntExist";
        File file = new File(fileName);

        if(file.exists())
        {
            FileReader fr = new FileReader(fileName);
            BufferedReader br = new BufferedReader(fr);
            String line;
            while((line = br.readLine()) != null)
            {
                System.out.println(line);
            }
        }
        else
        {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            System.out.println("Enter file Name:");
            String line;
            while(true)
            {
                line = br.readLine();
                File myFile = new File(line);
                if(myFile.exists())
                    break;
                else
                    System.out.println("Error, file doesn't exist!");
            }
            FileReader fr = new FileReader(line);
            BufferedReader br2 = new BufferedReader(fr);
            System.out.println("File contents:");
            while((line = br2.readLine()) != null)
            {
                System.out.println(line);
            }
        }
    }
}

截屏:


命令行截图

于 2012-11-13T23:09:01.153 回答
1

我认为您没有发布使用中的代码,您的错误应该与FileReaderImputStream.

使用InputStreamReader

BufferedReader in
   = new BufferedReader(new InputStreamReader(System.in));

完全按照文档中给出的:)

于 2012-11-13T23:16:49.350 回答