[英]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.