【问题标题】:After reading a file how to read line from a such postion (java)读取文件后如何从这样的位置读取行(java)
【发布时间】:2013-05-16 16:33:42
【问题描述】:

此代码可以读取许多文件并将它们显示在文本区域中。

例如:

...........> 12 16 17 18

...........> 15 17 ab cd

...........> 公元前 2g 广告

我想读取文件,但只能在字符位置 = 12 之后。 这是我正在使用的代码。

 FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
    File folder = new File("D:/bcc/");
    if (folder.isDirectory()) {
    for (File file : folder.listFiles()) {
    fileReader = new FileReader(file);
    bufferedReader = new BufferedReader(fileReader);
    String line = null;
    int lineCount = 0;
    while (null != (line = bufferedReader.readLine())) {
    lineCount++;

    if (1000 != lineCount) {

    jTextArea1.append(line +"\n");
    }
    }
    }
    }


    }
    catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (null != bufferedReader)
    try {
    bufferedReader.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

【问题讨论】:

  • 不清楚(对我而言)您要达到的目标。跳过“12”?
  • 我的意思是我想从 12 号克拉特读取行。
  • 所有文件都包含一个字符数 12 吗? 12号之前有内容吗?
  • 不,我的意思是字符的位置是12
  • 那么,您基本上是想跳过每个文件的前 12 个字符并阅读其余所有字符?

标签: java string file position


【解决方案1】:

要跳过每行的前 12 个字符,可以使用 String 的 substring(int) 方法。

替换:

jTextArea1.append(line + "\n");

与:

jTextArea1.append(((line.length() > 12) ? line.substring(12) : line) +"\n");

编辑
长度

【讨论】:

  • 呸问题:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-12
  • 我仍然不确定,这是否解决了您的真正问题。如果您给我们一些输入行和所需输出行的示例,可能会有所帮助。
  • 输入:L010 ---> (186251084) 10 09 3b 44 16 L010
  • 您收到的错误意味着您的文件中有空行。我更新了答案,以考虑少于 12 个字符的行(按原样打印)。
【解决方案2】:

在java中使用substring方法

例如

String sCurrentLine = "Your String";
sCUrrentLine = sCurrenline.subString(sCurrentline.indexOf("firstCharcter")+12);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多