所以我的问题是标题是怎么回事。下面是我的代码片段。我明白我应该使用try / 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*/
}
答案 0 :(得分: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);
}
}
}
}
屏幕截图:
答案 1 :(得分:1)
我认为您没有发布正在使用的代码,您的错误应与从FileReader
创建ImputStream
相关。
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));
完全按照文档中的说明完成:)