簡體   English   中英

逐行讀取ascii文件 - Java

[英]Reading ascii file line by line - Java

我正在嘗試讀取一個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 reader = new FileReader(file);
    int len = 0;
    int c;
    int iLine = 0;
    while( (c = reader.read()) != -1) {
        if( c == '\n' ){
            iLine++;
            System.out.println( "line " + iLine + " 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);
       }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM