hdfs写文件报错java.io.IOException: Filesystem closed

创建文件系统实例的时候使用下面:

 FileSystem  fs=FileSystem.newInstance(conf);

而不是用:fs = FileSystem.get(conf);

参考:https://blog.csdn.net/qiumengkai/article/details/48682143

参考:http://itxw.net/article/140.html

FileSystem get和newInstance区别

查看得到得源码:

<span style="color:#333333">public static FileSystem get(URI uri,Configuration conf)抛出IOException {
    String scheme = uri.getScheme();
    String authority = uri.getAuthority();
    if(scheme == null && authority == null){//使用默认FS
      //根据fs.defaultFS的值获取文件系统,若未设置该参数则根据文件:///返回文件系统
      return get(conf);
    }
    if(scheme!= null && authority == null){//无权限
      //根据fs.defaultFS的值创建URI,若未设置则使用文件:///创建URI
      URI defaultUri = getDefaultUri(con​​f);
      if(scheme.equals(defaultUri.getScheme())//如果scheme匹配default
          && defaultUri.getAuthority()!= null){//&default具有权限
        return get(defaultUri,conf); //返回默认值
      }
    }
    String disableCacheName = String.format(“fs。%s.impl.disable.cache”,scheme);
    if(conf.getBoolean(disableCacheName,false)){
      //根据URI和的conf创建文件系统
      return createFileSystem(uri,conf);
}
//若未设置缓存参数为真,则默认从CACHE中获取文件系统对象
    返回CACHE.get(uri,conf);
}</span>

总结:

从上面的代码可以得知,获得方法不是每次都创建文件系统对象,会从缓存中获取文件系统对象,而的newInstance方法则会每次都创建新对象。所以在使用该对象的API编程时,推荐使用获得方法。

 

注意:用得不能关闭,否则多线程报错(所以我用静态的),而用的newInstance必须每次接近。

猜你喜欢

转载自blog.csdn.net/laimao8079/article/details/88870565