无法使用java代码在linux运行时创建文件

jjhzyzn0  于 2021-06-25  发布在  Storm
关注(0)|答案(2)|浏览(426)

我正在编译maven项目,以便在linux机器上运行storm拓扑。
下面是bolt类中的一个方法,我想在运行时创建一个文件,缓冲读取器将从输入中收集数据并将其写入文件。
tuple input object:包含要写入的数据。
/root/data/javacode/top\u 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包编译项目时,它都会给出编译错误:

[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相关的代码时,它都能成功地工作。上述代码中提到了行号。代码有什么问题?

f8rj6qna

f8rj6qna1#

您需要指定函数execute抛出ioexception。

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

或者您可以捕获异常。这是在一个io操作失败的情况下。

mbzjlibv

mbzjlibv2#

尝试抛出ioexception或将代码环绕到trycatch块。

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

相关问题