这就是我所拥有的。。。我知道它应该需要一个循环,或者可能需要File类中的.empty((方法,但我不确定。。任何帮助都将不胜感激。我将打开一个文件,读取文件中的每一行,然后返回文件中的字符数、文件中的单词数和文件中的句子数。
public class FileExample{
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
boolean fileFound = false;
try{
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
if(!file.exists()){
}
while((line = reader.readLine()) != null){
if(!(line.equals(""))){
...
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
System.out.println("output data");
}
}
您需要制作一个while循环,并在循环中移动try块。
while(true){
try{
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
if(!file.exists()){
continue;
}
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
while((line = reader.readLine()) != null){
if(!(line.equals(""))){
characterCount += line.length();
String[] wordList = line.split("\s+");
countWord += wordList.length;
String[] sentenseList = line.split("[!?.:]+");
sentenseCount += sentenseList.length;
}
}
break;
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
}
使用while循环,直到文件存在。示例:
...
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
while(!fileFound){
System.out.println("The file does not exist. What is the name of the file?");
inputFile = in.nextLine();
file = new File(inputFile);
fileFound = file.exists();
}
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
...
在代码中添加do while。就像这样。不太确定它是否会运行,但我希望你明白的想法
do {
try {
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
while((line = reader.readLine()) != null){
if(!(line.equals(""))){
characterCount += line.length();
String[] wordList = line.split("\s+");
countWord += wordList.length;
String[] sentenseList = line.split("[!?.:]+");
sentenseCount += sentenseList.length;
}
}
} catch (FileNotFoundException e){
System.out.println("File not found.");
}
} while (!fileFound) {
System.out.println("Character count: "+characterCount);
System.out.println("Word count: "+countWord);
System.out.println("Sentence count: "+sentenseCount);
}