也许是这样:
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);
}
}
}
}
截屏: