从文件中读取可变数量的行

时间:2013-08-22 13:35:13

标签: java file-io inputstream

我试图从文件中读取可变数量的行,希望使用InputStream对象。我想要做的(在一般意义上)如下:

Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
   write to file

我知道InputStream是字节而不是行,所以我不确定这是否是一个很好用的API。如果有人对解决方案(其他API,不同算法)的看法有任何建议,那将非常有帮助。

2 个答案:

答案 0 :(得分:2)

你可以有这样的东西

       BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
       while (br.readLine() != null && linesWritten < maxLines) { 
         //Your logic goes here
        }

答案 1 :(得分:1)

看看这些:

Buffered ReaderBuffered Writer

//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
    while ((line = br.readLine()) != null) {
        allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
    }
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader

//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
    bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer
相关问题