[英]InputStream reading file and counting lines/words
我正在做一个项目,我想算数
1)字数。 2)文本文件中的行数。
我的问题是我无法弄清楚如何检测文件何时进入下一行,因此我可以正确地增加行数。 基本上,如果next不是空格,则递增单词;如果next是换行,则递增行。 我该怎么做? 谢谢!
public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNext()) {
if (f.next().equals("\n")) {
lines++;
} else if (!(f.next().equals(" "))) {
words++;
}
}
System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}
您必须使用InputStream吗? (是)最好将BufferedReader与传入的InputStreamReader一起使用,以便您可以逐行读取文件并在此过程中递增。
numLines = 0;
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null)
{
numLines++;
// process the line.
}
}
然后,要对单词进行计数,只需使用查找空格的正则表达式将字符串拆分即可。 myStringArray = MyString.Split(MyRegexPattern);
然后将返回所有单词的String[]
。 然后您要做的就是numWords += myStringArray.length();
尝试这个:
public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNextLine()) {
String line = f.nextLine();
lines++;
for (String token : line.split("\\s+")) {
if (!token.isEmpty()) {
words++;
}
}
}
System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}
请尝试以下操作:
public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNextLine()) {
String line = f.nextLine();
String[] arr = line.split("\\s");
words += arr.length;
lines++;
}
System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}
您可以使用InputStreamReader创建一个可以逐行读取文件的bufferedReader:
int amountOfLines = 0;
try {BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))} catch (Exception e) {e.printStackTrace();}
String line;
while ((line = br.readLine()) != null{
numLines++;
// process the line.
}
然后,您可以使用split(String)方法分离每个部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.