Java的;带有文件输入的输出中某些字符的新行

时间:2015-11-15 13:09:25

标签: java bufferedreader filereader fileoutputstream

基本上'{'和'}'需要在输出的新行上。但我不知道如何有效地阅读某些字符。我有一个程序读取行并输出它们,不知道从哪里开始。感谢

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

  try {
    FileReader reader = new FileReader("textfile.txt");
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line;        

    while ((line = bufferedReader.readLine()) != null) {
      System.out.println(line);
    }
    reader.close();

  } catch (IOException e) {
    e.printStackTrace();
  }
}

3 个答案:

答案 0 :(得分:1)

这是一种简单的方法(使用org.apache.commons.io进行文件解析):

解决方案

public static void main(String args[]) throws IOException {
    File testFile = new File("textfile.txt");
    String fileContent = FileUtils.readFileToString(testFile);
    fileContent = fileContent.replaceAll("\\{", "\n{").replaceAll("}", "\n}");
    System.out.println(fileContent);
}

解释

这会将文件读取为字符串并替换所有出现的&#39; <&#39; &#39;}&#39; 相应地使用&#39; \ n {&#39; &#39; \ n}&#39;

顺便说一下。只有&#39; <&#39; 字符需要通过&#39; \\&#39; 进行展开。

编辑:

如何使用该库。

看到您似乎是Java的新手,要使用该库,您有多个选项。其中之一就是使用项目管理工具,例如&#34; Apache Maven&#34;。

然而,最简单的选择是donwload the library(选择&#34; commons-io-2.4-bin.zip &#34;)。

将文件 commons-io-2.4.jar 解压缩到您的项目中。假设您有一个现代IDE,它将知道在代码中使用它时如何导入库。

答案 1 :(得分:0)

您可以使用String.replaceAll方法,然后添加新行并将{打印到新行

以下是如何做到这一点:

 public static void main(String[] args) throws IOException {
       try {
        FileReader reader = new FileReader("textfile.txt");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;





        while ((line = bufferedReader.readLine()) != null) {
         line=line.replaceAll("\\{", "\n{");
         line=line.replaceAll("\\}", "\n}");
            System.out.println(line);
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 2 :(得分:-1)

因为你想明智地阅读文件。不读行但是字符

while ((r = reader.read()) != -1) {
            char ch = (char) r;
           // do your work
        }
    }

如果您想出于某种原因首先阅读第一行 一个你得到的行

char[] chars = line.toCharArray();
for (Char char : chars)
{
    // check for that character and process accordingly
}