【问题标题】:how to use printwriter to create and write to a file [duplicate]如何使用printwriter创建和写入文件[重复]
【发布时间】:2014-08-14 01:09:28
【问题描述】:

我正在尝试使用 printwriter 类创建一个新文件并将数据打印到所述文件。

我的代码是这样的

File Fileright = new File("C:\\GamesnewOrder.txt"); 

PrintWriter pw = new PrintWriter(Fileright);

for(int i =0;i<=Games2.length-1;i++)
{
    pw.println(Games2[i]);

}

pw.close();

我确实有带有throwsIOException 的主要方法。

错误java.iofilenotfound 异常一直出现在我正在创建打印器的行。那么是打印机没有创建文件吗?

【问题讨论】:

  • 解释你所说的错误是什么意思。您是指编译时错误还是在运行时抛出Exception
  • java.io.FileNotFoundException: C:\GamesnewOrder.txt(访问被拒绝)(在 java.io.FileOutputStream 中)
  • 请把它放在你的问题中。
  • 您可能无法直接在 C:\ 文件夹中写入。尝试写入您的文档文件夹或类似的东西(我没有 Windows,所以我不能自己尝试)。
  • 这是您的答案stackoverflow.com/a/19309163/1031312。以后请在提出重复问题之前进行一些搜索。

标签: java file filenotfoundexception printwriter


【解决方案1】:

代码对我有用。

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

  public class NewClass {

     void n() throws FileNotFoundException {
             File Fileright = new File("/home/ubuntu/Documents/f.txt");

             PrintWriter pw = new PrintWriter(Fileright);

             for (int i = 0; i <= 3; i++) {
                pw.println(i);
                System.out.println(i);

             }

             pw.close();
      }

      public static void main(String[] args) throws FileNotFoundException {

             new NewClass().n();
      }

}

输出:(在文件中:/home/ubuntu/Documents/f.txt)

0
1
2
3

【讨论】:

    【解决方案2】:

    FileNotFoundException - 如果给定的文件对象不表示 现有的可写常规文件和该名称的新常规文件 无法创建,或者如果在打开或 创建文件

    请检查文件权限,您可以使用canRead()canWrite()检查,但可能不够。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多