【问题标题】:Not able to create file on runtime in linux using java code无法使用 java 代码在 linux 运行时创建文件
【发布时间】:2013-03-06 10:57:13
【问题描述】:

我正在编译 maven 项目以在 linux 机器上运行 Storm Topology。

以下是 Bolt 类中的一个方法,这里我想在运行时创建一个文件,其中缓冲的 Reader 将从输入中收集数据并将其写入文件。

元组输入对象:包含要写入的数据。
/root/data/javacode/top_output.csv:文件名。
代码中已经导入了所有的 IO 包。

public void execute(Tuple input, BasicOutputCollector collector) {
    String sentence = input.getString(0);
    String[] process = sentence.split(" ");
    File file = new File("/root/data/jcode/top_output.csv");
    if (!file.exists()) {
        file.createNewFile();
    }
    FileWriter fw = new FileWriter(file.getAbsoluteFile());  // line no. 36
    BufferedWriter bw = new BufferedWriter(fw);  
    for (String proc : process) {
        proc = proc.trim();
        if (!proc.isEmpty()) {
            collector.emit(new Values(proc));
            bw.write(proc);    // line no. 42
        }
    }
    bw.close();
}

每当我使用 mvn package 编译项目时,都会出现编译错误:

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ lgassStorm ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 4 source files to /root/data/lgassStorm/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /root/data/lgassStorm/src/main/java/lgaas/bolts/DataNormalizer.java:[36,19] error: unreported exception IOException; must be caught or declared to be thrown
[ERROR] /root/data/lgassStorm/src/main/java/lgaas/bolts/DataNormalizer.java:[42,13] error: unreported exception IOException; must be caught or declared to be thrown
[INFO] 2 errors

每当我评论 Filewriter 相关代码时,它都会成功运行。上面的代码中提到了行号。 代码有什么问题?

【问题讨论】:

    标签: linux java-io apache-storm


    【解决方案1】:

    您需要指定函数执行会抛出 IOException。

    public void execute(Tuple input, BasicOutputCollector collector) throws IOException {
    

    或者你可以捕获异常。这是为了防止其中一个 IO 操作失败。

    【讨论】:

      【解决方案2】:

      尝试抛出 IOException 或将您的代码包围到 TryCatch 块。

      public void execute(Tuple input, BasicOutputCollector collector){
      try{
      your code...
      }catch (IOException e){
      e.printStackTrace ();
      }
      }
      

      【讨论】:

      • 我也试过了,但是当文件系统的文件不存在时,代码给出编译错误,如果文件已经存在,则编译成功。
      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      相关资源
      最近更新 更多