我是 Java 编码新手。我将这段代码放在一起,以读取以下文本文件中“开始”和“结束”标记之间的所有行。
开始
嗨
你好
如何
是
你
在做什么?
结束
我的程序如下......
package test;
import java.io.*;
public class ReadSecurities {
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileInputStream in = new FileInputStream("U:\\Read101.txt");
FileOutputStream out = new FileOutputStream("U:\\write101.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
BufferedReader br = new BufferedReader(new InputStreamReader(in));
for (int i=1; i<=countLines("U:\\Read101.txt"); i++) {
String line=br.readLine();
while (line.contains("Start")) {
for (int j=i; j<=countLines("U:\\Read101.txt"); j++) {
String line2=br.readLine();
System.out.println(line2);
if(line2.contains("End")) break;
else {
bw.write(line2);
bw.newLine();
}
bw.close();
} break;
}
}
br.close();
}
catch (Exception e) { }
finally { }
}
}
程序只读取前两行“hi hello”,就好像 if 条件不存在一样。我感觉这个错误是非常基本的,但请纠正我。
最佳答案
String line;
do{ line = br.readLine(); }
while( null != line && !line.equals("Start"));
if ( line.equals("Start") ) { // in case of EOF before "Start" we have to skip the rest!
do{
line = br.readLine();
if ( line.equals("End") ) break;
// TODO write to other file
}while(null != line )
}
应该就这么简单。为了简洁起见,我省略了资源的创建/销毁和正确的异常处理。
但是请至少记录异常!
编辑:
如果在开始之前遇到EOF,则必须跳过复制步骤!
关于java程序有条件地从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993396/