gpt4 book ai didi

java - 需要计算文本文件中的字符数

转载 作者:行者123 更新时间:2023-11-30 07:54:09 25 4
gpt4 key购买 nike

我必须编写代码来读取文本文件并告诉我文件中有多少行和字符。我让它工作了,但后来我意识到我必须忽略空白间隙,所以我写了一个方法来做到这一点。它对于一行工作正常,但如果我有多于一行,它似乎会计算任何空白。任何帮助将不胜感激

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) {
}
}

}

关于java - 需要计算文本文件中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32913860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com