【问题标题】:FileOutputStream doesn't create fileFileOutputStream 不创建文件
【发布时间】:2016-06-09 02:25:33
【问题描述】:

FileOutputStream does not create file 的完全重复

我在 Eclipse 中运行以下代码,这是我从那个问题中得到的。没有创建文件。

BufferedOutputStream dob = null;
    try {
        File file = new File("C:\\Users\\claudio\\ccc.as");
        System.out.println("file created:" + file.exists());
        FileOutputStream fod = new FileOutputStream(file);
        System.out.println("file created:" + file.exists());
        dob = new BufferedOutputStream(fod);
        byte[] asd = {65, 22, 123};
        byte a1 = 87;
        dob.write(asd);
        dob.write(a1);
        //dob.flush();
    } 
    catch (Exception ex) {
        ex.printStackTrace();
    }
    finally {
        if (dob != null) {
            try {
                dob.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

Eclipse 建议使用第二个 try/catch 覆盖 .close()。我可能犯了一个明显的错误,如果是这样,请原谅我。

【问题讨论】:

  • 您是否在 Eclipse 调试器中运行过它?我的猜测是您的程序没有访问 `C:\Users\claudio` 的权限,并且它在 Eclipse 的控制台选项卡中输出了一个异常。
  • 您有对该目录的写入权限吗?请尝试手动创建文件。
  • 我认为不用说没有抛出异常。

标签: java eclipse fileoutputstream


【解决方案1】:

简单,

byte[] asd = {65, 22, 123};
FileOutputStream out = new FileOutputStream("C:\Users\claudio\ccc.as");
out.write(data);
out.close();

如果您使用的是 Java 7+,

byte[] asd = {65, 22, 123};
Path file = Paths.get("C:\Users\claudio\ccc.as");
Files.write(file, asd);

【讨论】:

    【解决方案2】:

    我会尝试this example,它使用createNewFile() 来执行预期的行为。我认为您使用的方法不会自动创建一个。

    文件可以使用如下方式实例化:

    File file = new File("MyFile.txt");
    file.createNewFile();
    

    【讨论】:

      猜你喜欢
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多