当我在终端中运行程序时,我需要程序读取任何文本文件,所以如果它看起来像这样:
01.txt中的java TextAnalysis,当我按回车键时。如果我有一个特定的文本文件被扫描仪读取,我知道一切都能正确编译。但是当我尝试用args替换该文件时,它停止了编译,并给出了一个错误:
Exception in thread "main" java.io.FileNotFoundException: in01.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at TextAnalysis.main(TextAnalysis.java:17)来源:
import java.util.*;
import java.io.*;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName));
System.out.println("Word-frequency statistics");
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}发布于 2014-03-12 11:08:35
您的文件名中有一个空格,这使得java将您的参数解释为数组{TextAnalysis,in01}。解决此问题的简单方法是将文件名中的空格设置为下划线。
发布于 2014-03-12 11:14:46
由于您在01.txt中的文件不存在,因此当您尝试使用此文件中的扫描仪时,抛出异常。
确保在TextAnalysis.class所在的目录中有一个名为in01.txt的文件。
https://stackoverflow.com/questions/22341194
复制相似问题