java nio Files.write() method not working

假装没事ソ 提交于 2019-12-13 09:23:59

问题


Okay, so I'm trying to use the new Files.write method in Java. Here is a link

It says the StandardOpenOption is optional, but everytime I leave it blank, and even when I do put something in there I get a compiler error. For Example...

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

will result in The method write(Path, byte[], OpenOption...) in the type Files is not applicable for the arguments (Path, String)


回答1:


This has nothing to do with NIO and everything to do with language syntax. You have:

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

I don't know what your intention is with that, but you can't declare a variable in a function parameter list like that. You probably mean something like:

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

For a more formal view, dig around through the JLS, starting at JLS 15.12. There is ultimately no ArgumentList pattern in the language that can accept a LocalVariableDeclarationStatement.




回答2:


If i change it to

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

i see

no suitable method found for write(String,byte[])
Files.write("example.txt", new byte[0]);
^ method Files.write(Path,Iterable,Charset,OpenOption...) is not applicable (actual argument String cannot be converted to Path by method invocation conversion)
method Files.write(Path,byte[],OpenOption...) is not applicable (actual argument String cannot be converted to Path by method invocation conversion)
1 error

And if i change to

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

Then i have no compiler warnings.

So, you need:

  1. Change String parameter to Path parameter
  2. Use byte array variable "byteArray" instead of "byte[] byteArray" because the latter one is an input parameter signature.


来源:https://stackoverflow.com/questions/20011101/java-nio-files-write-method-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!