[英]Need to count characters in text file
我必須編寫代碼來讀取文本文件,並告訴我文件中有多少行和字符。 我可以使用它,但是后來我意識到我必須忽略空白間隙,所以我寫了一種方法來做到這一點。 它對於一行來說效果很好,但是如果我多於一行,它似乎可以算出任何空格。 任何幫助,將不勝感激
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Inputfile {
public static void main(String[] args) {
System.out.println("file name:");
Scanner sc = new Scanner(System.in);
String fn = sc.next();
int nrl = 0, nChar = 0;// nrl for number of lines
String line;// get line content variable
try {
File fs = new File("C:/" + fn);
nChar = length_ws(fs);
FileReader fr;// for reading file
fr = new FileReader(fs);
LineNumberReader lnr = new LineNumberReader(fr);
while (lnr.readLine() != null) {
nrl++;// count number of lines
}
JOptionPane.showMessageDialog(null, "number of lines:" + nrl + "\ntotal number of chars:" + nChar);
lnr.close();
fr.close();// close file
} catch (FileNotFoundException ex) {
System.err.println("File not found");
System.exit(0);
} catch (IOException ex) {
}
}
public static int length_ws(File f) throws IOException {
FileReader fr = null;
fr = new FileReader(f);
int i;
i = 0;
int c = 0;
do {
c = fr.read();// read character
if (c!= ' ') // count character except white space
i++;
} while (c != -1);
return i - 1;// because the is counted even the end of file
}
}
我不認為它正在讀取空格,而是換行符(因為這些字符是字符)。
我建議您只讀取一次文件(現在看來您讀取了兩次)。
當char到達時
c = fr.read()
您評估是哪個字符,請檢查asci表ASCII TABLE ,您有空格,制表符和換行符(請注意,根據格式,可以有兩個字符LF和CR作為換行符)
如果您有有效的字符,請提前輸入字符計數器。 如果您有有效的換行字符,則可以增加行數。
希望對您有所幫助,並改善您的編碼,祝您好運
看到您的評論,我添加了此代碼,它不是完美的,只是一個開始
int LF = 10; // Line feed
int CR = 13; // Chr retrun
int SPACE = 32;// Space
int TAB = 9; // Tab
FileReader fr = null;
int numberOfChars = 0;
int numberOfLines = 0;
int c = 0;
try {
do {
fr = new FileReader(new File("fileName.txt"));
c = fr.read();// read character
if (c > SPACE) { // space (ignoring also other chars
numberOfChars++;
}
if (c == LF) { // if does not have LF try CR
numberOfLines++;
}
} while (c != -1);
} catch (Exception e) {
e.printStackTrace();
if (fr != null) {
try {
fr.close();
} catch (IOException e1) {
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.