简体   繁体   English

创建和写入文件

[英]Creating and Writing to a File

if (!file.exists())
  file.mkdirs();
  file.createNewFile();

The error states that I have a problem with actually 'writing' Go Falcons to the file, it will state that the file access is denied, Does that mean something is wrong with my code? 该错误表明我实际上将Go Falcons“写入”文件时遇到问题,它将指出文件访问被拒绝,这是否意味着我的代码有问题?

Error states: FileNotFoundException Access is denied 错误状态:FileNotFoundException访问被拒绝

PS: how do I actually read this file, once it's writable? PS:一旦可写,我如何实际读取该文件?

Change: 更改:

if (!file.exists())
  file.mkdirs();
  file.createNewFile();

To: 至:

if (!file.exists()) {
  file.createNewFile();
}

But first, go read some tutorials or articles. 但首先,请阅读一些教程或文章。 Why are you extending Exception ? 为什么要扩展Exception

If I understand your question, one approach would be to use a PrintWriter 如果我理解您的问题,一种方法是使用PrintWriter

public static void main(String[] args) {
  File outFile = new File(System.getenv("HOME") // <-- or "C:/" for Windows.
      + "/hello.txt");
  try {
    PrintWriter pw = new PrintWriter(outFile);
    pw.println("Go Falcons");
    pw.close();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
}

Which creates a single line ascii file in my home folder named "hello.txt". 这将在我的主文件夹中创建一个名为assii的单行文件“ hello.txt”。

$ cat hello.txt
Go Falcons

Your problem is that right before you attempt to create your output file, you first create a directory with the same name: 您的问题是,在尝试创建输出文件之前,首先要创建一个具有相同名称的目录:

            if (!file.exists())
                file.mkdirs();      // creates a new directory
            file.createNewFile();   // fails to create a new file

Once you've already created the directory, you can no longer create the file, and of course, you cannot open a directory and write data to it as if it were a file, so you get an access denied error. 一旦创建了目录,就无法再创建文件,当然,您无法像打开文件一样打开目录并向其中写入数据,因此会出现拒绝访问错误。

Just delete the file.mkdirs(); 只需删除file.mkdirs(); line and your code will work fine: 行,您的代码将正常运行:

        if (!file.exists())
            file.createNewFile();   // creates a new file

You can take the substring of the path till folder structure(excluding file name) and create directories using method mkdirs() . 您可以使用路径的子字符串直到文件夹结构(文件名除外),然后使用方法mkdirs()创建目录。 Then create file using createNewFile() method. 然后使用createNewFile()方法创建文件。 After that write to newly created file. 之后,写入新创建的文件。 Don't forget to handle exceptions. 不要忘记处理异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM