【问题标题】:This code is showing errors.What is wrong with this code? [duplicate]此代码显示错误。此代码有什么问题? [复制]
【发布时间】:2016-08-03 13:40:59
【问题描述】:
File file = new File("D:/projects/tFile.txt") ;
        file.createNewFile();  //Unhandled exception type IOException
        FileOutputStream fout = new FileOutputStream(file); //Unhandled exception type FileNotFoundException
        String s = "Cricket";
        byte []b = s.getBytes();
        fout.write(b);//Unhandled exception type IOException
        fout.close();// Unhandled exception type IOException

这显示了 FileNotFound Exception 和 IoException。

【问题讨论】:

  • 当您对错误有疑问时,请确保在您的问题中包括错误是编译时还是运行时、错误发生在哪一行以及完成 错误文本。
  • 您是否费心在 Google 上搜索这些错误以努力了解它们是什么、为什么会发生以及可能有哪些潜在的修复方法?
  • 您是否阅读过错误消息?

标签: java


【解决方案1】:

它要求您处理从您使用的方法中抛出的异常。

将它们包围在 try catch 块中。

public void method(){
        try {
            File file = new File("D:/projects/tFile.txt") ;
            file.createNewFile();
            FileOutputStream fout = new FileOutputStream(file);
            String s = "IPL is very entertaining tournament";
            byte []b = s.getBytes();
            fout.write(b);;
            fout.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

【讨论】:

  • 这并不能真正修复问题。
  • 您能详细说明一下吗?
  • 所有这些都是为了防止异常导致程序崩溃。仍然抛出异常并且问题没有解决。因此,我认为这不是一个有效的答案。
  • docs.oracle.com/javase/6/docs/api/java/io/… 根据 Javadoc API 创建新文件会引发 IOException。代码会在不添加异常处理的情况下编译吗?
  • 但是如果是权限问题怎么解决呢?
【解决方案2】:

这执行得很好。可能是你的 D:/projects 丢失了。 或者可能是由于异常

public static void main(String[] args) throws IOException {
    File file = new File("D:/Test/tFile.txt") ;
    file.createNewFile();
    FileOutputStream fout = new FileOutputStream(file);
    String s = "IPL is very entertaining tournament";
    byte []b = s.getBytes();
    fout.write(b);;
    fout.close();
}

【讨论】:

  • 这应该是一条评论。
  • 不,D:/projects 没有丢失。路径正确。
  • 您是否真的尝试将其放入 Eclipse 中。你能编译它吗?
猜你喜欢
  • 2018-12-21
  • 2015-10-22
  • 1970-01-01
  • 2023-03-31
  • 2012-05-08
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 2012-04-11
相关资源
最近更新 更多