逐行读取ascii文件 - Java

时间:2015-10-25 12:19:39

标签: java netbeans ascii

我正在尝试读取ascii文件并识别换行符的位置" \ n"至于我知道每行中有哪些字符和多少字符。文件大小为538MB。当我运行以下代码时,它从不打印任何东西。 我搜索了很多,但我没有找到任何ascii文件。我使用netbeans和Java 8.任何想法??

以下是我的代码。

<md-sidenav md-is-locked-open="isSideNavOpen">...</md-sidenav>

$scope.openLeftMenu = function() {
  $scope.isSideNavOpen = !$scope.isSideNavOpen;
};

3 个答案:

答案 0 :(得分:1)

将文件内容存储到字符串的方法:

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

找到herehere

答案 1 :(得分:0)

一行中的字符数是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();

答案 2 :(得分:-1)

您应该使用FileReader这是读取字符文件的便利类。

FileInputStream javs docs clearly states

  

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