【问题标题】:BufferedWriter creates empty file with nothing insideBufferedWriter 创建空文件,里面什么都没有
【发布时间】:2016-10-27 13:23:52
【问题描述】:

我有以下代码:

FileSystem fs = FileSystem.get(context.getConfiguration());    
Path filePath2 = Path.mergePaths(outputPath, new Path( "/SomeFile"));
            BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(fs.create(filePath2,true)));
            writer2.write("Key: " + key.toString() + "\nValue: " + values.iterator().next().getSensCol().toString());

            writer2.close();

我正在为其中一些类使用 Hadoop 库。执行后,我看到文件已创建,但里面没有任何内容,有什么想法吗?

【问题讨论】:

  • flush 不是必需的,因为关闭会导致内部刷新。
  • 变量fs中有什么?
  • 文件系统 fs = FileSystem.get(context.getConfiguration());
  • 标准API中只有java.nio.file.FileSystem,没有get方法...
  • 代码不完整。发布一个最小的工作样本。否则我只会猜测 keynull 并且你会吞下 NPE。

标签: java hadoop outputstream bufferedwriter


【解决方案1】:

没有足够的信息进行正确的诊断,但您的代码看起来是正确的......除了(可能)路径。在 Linux 系统上(至少)普通用户应该无法将文件写入“/”目录。

所以,我可以提出几个可能的解释:

  1. 正在写入文件,但未写入您正在查看的目录。

  2. 文件打开失败(或写入失败)但您的应用程序挤压异常...在一些您没有向我们展示的代码中。


啊!看起来您正在使用 org.apache.hadoop.fs.FileSystem ! (FileSystem 类的java.nio.file 版本没有get 方法。)

我认为这不会改变我的答案,除了关于能够写入“/”目录的内容。对于 Hadoop FS,这可能是允许的。

【讨论】:

    【解决方案2】:

    FileWriterBufferedWriter 一起使用。

    Path filePath2 = Path.mergePaths(outputPath, new Path( "/SomeFile"));
    
    FileWriter fileWriter2 = null;
    BufferedWriter writer2 = null;
    
    try {
        fileWriter2 = new FileWriter( filePath2.toFile() );
        writer2 = new BufferedWriter( writer2 );
    
        writer2.write("Key: " + key.toString() );
    
        //if you are going to use an Iterator, you better actually use it.
        for ( Iterator iterator = col.iterator() ; iterator.hasNext() ; ) {
            writer2.write( "\nValue: " + iterator.next()
                .getSensCol().toString() );
        }
    
    }
    catch ( IOException ex ) {
        //Exception handling
    }
    finally {
        writer2.close();
        fileWriter2.close();
    }
    

    我希望我有所帮助。

    祝你有美好的一天。 :)

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多