无法在java中创建文件(及其目录)后写入文件

the*_*dZA 0 java xml fileoutputstream printwriter java-io

我试图从Internet下载XML文件,然后将此文件放在目录(C:/ Nationstates)中.

File theDir = new File("/NationStates");

  if (!theDir.exists()) {
    System.out.println("creating directory: /NationStates" );
    boolean result = false;

    try{
        theDir.mkdir();
        result = true;
     } catch(SecurityException se){
       System.out.println("Dir exists");
     }        
  }

  new PrintWriter("/NationStates/NS.xml");

  URL website = new URL("https://www.nationstates.net/cgi-bin/api.cgi?nation=ageena");
  ReadableByteChannel rbc = Channels.newChannel(website.openStream());
  FileOutputStream fos = new FileOutputStream("/NS.xml");
  fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
  fos.close();
Run Code Online (Sandbox Code Playgroud)

我可以创建目录,并创建文件(NS.XML)但是当我尝试写入文件时,我收到以下错误:

Exception in thread "main" java.io.FileNotFoundException: \NS.xml (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at XML.main(XML.java:31)
Run Code Online (Sandbox Code Playgroud)

它表示访问被拒绝,但我刚刚在同一位置的该目录中创建了一个目录和一个文件.

任何想法如何解决这一问题?

JB *_*zet 5

您创建一个目录:

File theDir = new File("/NationStates");
...
theDir.mkdir();
Run Code Online (Sandbox Code Playgroud)

但是你不要写入这个目录中的文件:

FileOutputStream fos = new FileOutputStream("/NS.xml");
Run Code Online (Sandbox Code Playgroud)

而且,mkdir()不一定会创建目录.如果失败,则返回false.但是你不检查返回的值.