[英]Reading a variable number of lines from a file
I am trying to read a variable number of lines from a file, hopefully using InputStream object. 我试图从文件中读取可变数量的行,希望使用InputStream对象。 What I'm trying to do (in a very general sense) is as follows: 我正在尝试做的事情(从一般意义上来说)如下:
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
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. 我知道InputStream是按字节而不是行,因此我不确定这是否是一个很好的API。 If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful. 如果有人对解决方案(其他API,不同的算法)有什么建议,那将非常有帮助。
You can have something like this 你可以有这样的东西
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these: 看看这些:
Buffered Reader and Buffered 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.