【问题标题】:File input, String manipulation and output文件输入、字符串操作和输出
【发布时间】:2015-12-01 14:38:44
【问题描述】:

我正在尝试获取一个格式不正确的文件(例如 txt 代码文件),然后使用“制表符”将括号推到正确的位置来格式化它。但是使用我的代码它不会打印第一个括号。请注意,第一个和最后一个括号必须保持不变。谢谢

  @SuppressWarnings("unused")
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader("NewStripped.txt"));
    PrintWriter pw = new PrintWriter(new FileWriter("FinalStripped.txt"));
    String line; 
    int count = 0;
    try{
      while ((line = br.readLine()) != null) {
        count++;
        if (line != null){
          line = line.replaceAll("\\{", "\t{");
        } else if(line.contains("}")) {
          line = line.replaceAll("}","\t}");
        }                                       
        pw.println(line);
        System.out.println(line);
      }
      pw.close();
    } catch(Exception e) {
      e.printStackTrace();          
    }
  }
}

【问题讨论】:

  • if(count != 1) 将适用于除第一行之外的所有内容,第一行可能不包含任何右大括号。
  • 顺便说一句,您是否不想在与其级别(从零开始)相对应的左大括号之前添加多个制表符,即级别 2 上的大括号(具有 2 个“外部”大括号)将由 2 个选项卡设计?如果是这样,您可能想要更改代码并计算左大括号,即在每个左大括号上递增计数器并在每个右大括号上递减。然后在每个大括号前添加 count-1 个制表符。
  • 正则表达式错误:行 = line.replaceAll("\\{", "\t\\{");, line.replaceAll("\\}","\t\\}");

标签: java bufferedreader readline replaceall


【解决方案1】:

计算深度级别。

int count = -1;
...
while ((line = br.readLine()) != null) {
    if(line.contains("{")){
        count++;
        for(int i = 0; i < count; i++)
             line = line.replaceAll("\\{", "\t\\{");
    } else if(line.contains("}")) {
        for(int i = 0; i < count; i++)
             line = line.replaceAll("\\}","\t\\}");
        count--;
    }                                       
    pw.println(line);
    System.out.println(line);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多