java程序有条件地从文件中读取行

标签 java fileparsing

我是 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/

相关文章:

java - @SpringBootTest 需要数据库连接吗?

python - 尝试打开现有文件时出现 IOError

bash - "wc"命令的行为是什么?

python - 解析换行分隔文件

python - 在 celery 任务之间共享对象

java - hprof 探查器输出不包括行号,无论 `lineno` 值如何

java - JPA.withTransaction 执行其他 Controller 方法错误 : Global. java:39: 错误: 'void' 此处不允许类型

java - Java 中将 String 转换为 UUID 的最简单方法

Java Servlet 3.0 规范建议公开 X-Powered-by。这不是安全不良做法吗?