我试图读取一个ascii文件,并识别换行字符"n"的位置,以了解每行中有哪些字符和多少字符。文件大小为538MB。当我运行下面的代码时,它从不打印任何东西。我搜索了很多,但我没有找到任何ascii文件。我使用netbeans和Java 8。有什么想法?
下面是我的代码。
String inputFile = "C:myfile.txt";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
int BUFSIZE = 512;
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE);
Charset cs = Charset.forName("ASCII");
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
CharBuffer chbuf = cs.decode(buf);
for ( int i = 0; i < chbuf.length(); i++ ) {
if (chbuf.get() == 'n'){
System.out.println("PRINT SOMETHING");
}
}
}
将文件内容存储为字符串的方法:
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
下面是查找一个字符在整个字符串中出现的次数的方法:
public static void main(String [] args) throws IOException
{
List<Integer> indexes = new ArrayList<Integer>();
String content = readFile("filetest", StandardCharsets.UTF_8);
int index = content.indexOf('n');
while (index >= 0)
{
indexes.add(index);
index = content.indexOf('n', index + 1);
}
}
一行的字符数是readLine
调用读取的字符串的长度:
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
int iLine = 0;
String line;
while ((line = br.readLine()) != null) {
System.out.println( "Line " + iLine + " has " +
line.length() + " characters." );
iLine++;
}
} catch( IOException ioe ){
// ...
}
注意(依赖于系统的)行结束标记已被readLine
从字符串中删除。
如果一个非常大的文件不包含换行符,则确实有可能耗尽内存。逐字符读取可以避免这种情况。
<>之前File File = new File("Z.java");Reader = new FileReader(文件);Int len = 0;int c;int line = 0;While ((c = reader.read()) != -1) {If (c == 'n'){iLine + +;system . out。println("line " + illine + " contains " +)Len + " characters");Len = 0;} else {len + +;}}reader.close ();您应该使用FileReader,这是用于读取字符文件的方便类。
FileInputStream javs docs明确说明
FileInputStream用于读取原始字节流,例如图像数据。对于字符流的阅读,请考虑使用FileReader .
尝试下面
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
for (int pos = line.indexOf("n"); pos != -1; pos = line.indexOf("n", pos + 1)) {
System.out.println("\n at " + pos);
}
}
}