【问题标题】:Java; New line for certain character in output with a file input爪哇;带有文件输入的输出中某些字符的新行
【发布时间】:2015-11-15 13:09:24
【问题描述】:

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

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();
  }
}

【问题讨论】:

  • 输入文件将是一个简单的 java 类,其中 { 和 } 与代码位于同一行,例如 { public static void main(String [] argv),我想将其分开。
  • 如果您只想修复代码的格式,请使用astyleindent 之类的工具。
  • 谢谢,但我需要为它写一段代码。
  • 然后您可以使用 Apache Fileutils readFileToString() 将文件内容读入字符串,并使用 String.replace()String.replaceAll() 之类的方法。将{ 替换为\n{ 等。该程序将是几行代码。 docs.oracle.com/javase/7/docs/api/java/lang/…

标签: java bufferedreader filereader fileoutputstream


【解决方案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);
}

说明

这会将文件读取为字符串,并将所有出现的 '{''}' 替换为 '\n{' 或 '\n}' 对应。

顺便说一句。只有 '{' 字符需要通过 '\\' 进行分隔。

编辑:

如何使用库。

看到您似乎是 Java 新手,要使用该库,您有多种选择。其中之一是使用项目管理工具,例如“Apache Maven”。

但最简单的选择是donwload the library(选择“commons-io-2.4-bin.zip”)。

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

【讨论】:

    【解决方案2】:

    您可以使用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();
        }
    }
    

    【讨论】:

      【解决方案3】:

      因为您想明智地读取文件字符。不要读行而是读字符

      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
      }
      

      【讨论】:

      • downvoter 请帮助我改进解释这里有什么问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 2016-01-29
      相关资源
      最近更新 更多