【问题标题】:java nio Files.write() method not workingjava nio Files.write()方法不起作用
【发布时间】:2013-11-29 10:30:23
【问题描述】:

好的,所以我正在尝试在 Java 中使用新的 Files.write 方法。 Here is a link

它说 StandardOpenOption 是可选的,但每次我把它留空,即使我确实在那里放了一些东西,我也会得到一个编译器错误。比如……

try{
 Files.write("example.txt",byte[] byteArray);
 }
  catch(Exception e){}

会导致 Files 类型中的方法 write(Path, byte[], OpenOption...) 不适用于参数 (Path, String)

【问题讨论】:

  • 什么是byte[] byteArray 作为参数?你认为这有什么作用?

标签: java parameter-passing


【解决方案1】:

这与 NIO 无关,与语言语法有关。你有:

Files.write("example.txt",byte[] byteArray);

我不知道你的意图是什么,但你不能像这样在函数参数列表中声明变量。你的意思可能是这样的:

byte[] byteArray = ...; // populate with data to write.
Files.write("example.txt", byteArray);

要获得更正式的视图,请浏览 JLS,从 JLS 15.12 开始。语言中最终没有ArgumentList 模式可以接受LocalVariableDeclarationStatement

【讨论】:

  • 我正在尝试使用Files.write(path, str.getBytes(charset)),但即使第三个参数是可选的,它也会显示The method write(Path, byte[], OpenOption[]) in the type Files is not applicable for the arguments (Path, byte[])
【解决方案2】:

如果我把它改成

try{
    Files.write("example.txt", new byte[0]);
 } catch(Exception e){} 

我明白了

没有找到适合 write(String,byte[]) 的方法
Files.write("example.txt", new byte[0]);
^ 方法 Files.write(Path,Iterable,Charset,OpenOption...) 不适用(实际参数 String 无法通过方法调用转换为 Path 转换)
方法 Files.write(Path,byte[],OpenOption...) 不适用(实参String无法通过方法调用转换为Path)
1 个错误

如果我改成

 Path path = FileSystems.getDefault().getPath("logs", "access.log");
 try{
     byte[] byteArray = ...; // populate with data to write.
     Files.write(path, byteArray);
 } catch(Exception e){} 

然后我没有编译器警告。

所以,你需要:

  1. 将字符串参数更改为路径参数
  2. 使用字节数组变量“byteArray”而不是“byte[] byteArray”,因为后者是输入参数签名。

【讨论】:

  • 我想指出,您可以通过在您的 File 对象上调用 File#toPath() 来创建一个 Path 给定一个 File
  • 啊,是的,我是个笨蛋。谢谢你帮我解决这个问题
猜你喜欢
  • 2019-02-22
  • 2012-12-25
  • 1970-01-01
  • 2016-02-09
  • 2016-04-15
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多