0

我正在尝试从文件中读取可变数量的行,希望使用 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,不同的算法)有什么建议,那将非常有帮助。

4

2 回答 2

2

你可以有这样的东西

       BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
       while (br.readLine() != null && linesWritten < maxLines) { 
         //Your logic goes here
        }
于 2013-08-22T13:47:41.460 回答
1

看看这些:

缓冲读取器缓冲写入器

//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
于 2013-08-22T14:03:43.663 回答