Java FileIO错误没有分析所有类

时间:2014-04-29 21:24:57

标签: java file-io iterator

我正在尝试创建一个jar文件,该文件分析目录中的所有文件,查找提供的String并将其替换为提供的字符串+ .getInstance(),我有以下代码:

public static String toAnalyze;
    public static String path;

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java InstanceFixer <To Analyze> <Path>" );
            System.exit(1);
        }

        toAnalyze = args[0];
        path = args[1];

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        Date resultDate = new Date(System.currentTimeMillis());
        LoggingUtils.log("Instance Fixer","Started InstanceFixer on analysis " + toAnalyze + " at " + sdf.format(resultDate));

        startIterating();
    }

    public static void startIterating() {
        File dir = new File(path);
        System.out.println(dir);
        File[] directoryListing = dir.listFiles();
        if (directoryListing != null) {
            for (File child : directoryListing) {
                    filterFile(child);
            }
            LoggingUtils.log("Iterator","Analyzed " + directoryListing.length + " files.");
        } else {
            LoggingUtils.log("Iterator", path + " is not valid \n won't be able to Analyze files (if any).");
        }
    }

    public static void filterFile(File file) {
      try {
          BufferedReader in = new BufferedReader(new FileReader(file));
          BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
          String read = in.readLine();
              if (read.contains(toAnalyze + "Manager")) {
                  out.write(read.replace(toAnalyze + "Manager", toAnalyze + "Manager.getInstance()"));
                  LoggingUtils.log("Filter","Analyzed file " + file.getName() + ", found and fixed instance.");
                  out.close();
              } else {
                  LoggingUtils.log("Filter","Analyzed file " + file.getName() + ", didn't find anything to rename, skipped.");
              }
          in.close();
      } catch (IOException e) {
          LoggingUtils.log("Filter","There was a problem: " + e);
          e.printStackTrace();
      }
    }

问题在于它只搜索第一行或最后一行而不是替换文本,而是将其写入旧文本的一侧。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

  

而不是替换文本,而是将其写入旧文本的一侧

new FileWriter(file, true)参数true中设置append选项意味着编写者将在文件末尾添加新内容。另一方面,将其设置为false意味着将清理文件,编写器将从头开始编写它(如果它包含多行,则可能不是您想要的那样)。

但无论如何,你不应该同时阅读和写入你正在分析的同一个文件  相反

  • 创建新的临时文件
  • 遍历原始文件的所有行,
  • 将行写入临时文件 - 包含您想要的更改。
  • 删除原始文件
  • 将临时文件重命名为与原始文件同名。

示例:假设我们要添加包含行号的行新列,因此实际上我们要编辑每一行并在其开头添加类似xxx:的内容x表示数字(或空格,如果号码没有三位数)。所以我们可以像

那样做
try {
    File original = new File("input.txt");
    File tmp = new File("tmp.txt");
    BufferedReader in = new BufferedReader(new FileReader(original));
    PrintWriter out = new PrintWriter(new BufferedWriter(
            new FileWriter(tmp)));
    String line = null;
    int i = 1;
    while ((line = in.readLine()) != null) {
        out.format("%3d: %s%n", i++, line);// %d digit, %s string, %n
                                            // line separator
    }
    in.close();
    out.close();

    // lets swap files
    if (original.delete()) {
        System.out.println("original file removed");
        if (tmp.renameTo(original)) {
            System.out
                    .println("temporary file renamed to original file");
        } else {
            System.out.println("temporary file couldn't be renamed");
        }
    } else {
        System.out.println("original file couldn't be removed");
    }

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