如何在Java中使用PrintWriter和File类? [英] How to use PrintWriter and File classes in Java?

查看:126
本文介绍了如何在Java中使用PrintWriter和File类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解PrintWriter我正在制作的一个小程序,我似乎无法让java生成该文件然后在其上写。当我执行下面的程序时,它在第9行给出了一个Filenotfoundexeption错误。它也无法在我指定的目录中生成该文件。我是新手,所以请尽量保持简单的答案。我正在使用Eclipse。

I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.

import java.io.PrintWriter;
import java.io.File;

public class Testing {

  public static void main(String[] args) {

    File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
    PrintWriter printWriter = new PrintWriter ("file.txt");
    printWriter.println ("hello");
    printWriter.close ();       
  }
}


推荐答案

如果您需要创建它的目录不存在。 Java不会自己创建它,因为文件类只是一个实际上根本不存在的实体的链接。

If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.

正如您所述,错误是无法创建文件。如果您阅读PrintWriter构造函数的文档,您可以看到

As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see


FileNotFoundException - 如果给定的字符串不表示现有的可写常规文件和无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误

FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

您应该尝试创建一个它之前包含的文件夹的路径:

You should try creating a path for the folder it contains before:

File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();

PrintWriter printWriter = new PrintWriter(file);

这篇关于如何在Java中使用PrintWriter和File类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆