有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java读/写访问异常FileNotFoundException(访问被拒绝)

这里我有两种方法

private boolean readData(){
    if (!new File(config).exists()) {
        return false;
    } else {
        Hashtable<String, String> data;
        FileInputStream fis;
        try {
            fis = new FileInputStream(config);
            ObjectInputStream oin = new ObjectInputStream(fis);
            data = (Hashtable<String, String>) oin.readObject();
            username = data.get("username");
            password = data.get("password");
            folder = data.get("folder");
            fis.close();
            oin.close();
            return true;
        } catch (FileNotFoundException fnfe) {
            return false;
        } catch (IOException ioe) {
            return false;
        } catch (ClassNotFoundException cnfe) {
            return false;
        }
    }
}

private boolean writeData() {
    try {
        FileOutputStream fos = new FileOutputStream(config);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        Hashtable<String, String> data = new Hashtable<>();
        sout(username);
        data.put("username", username);
        data.put("password", password);
        data.put("folder", folder);
        oos.writeObject(data);
        oos.flush();
        oos.close();
        Runtime.getRuntime().exec("attrib +H " + config);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

我找不到关于堆栈溢出的答案

顺便说一下-异常总是从writeDataFileOutputStream抛出

附加说明
我忘了加。当程序第一次启动时,它成功地记录了文件数据。同样,它从文件中读取数据总是没有问题的。当我试图重写这个文件时,问题出现了

        if(new File(config).canWrite()){
            sout("Can write");
        } else{
            sout("I can't write");
        }
        writeData();

正在打印,我不会写,但实际上可以。我的意思是,文件出现,数据成功写入其中


共 (2) 个答案

  1. # 1 楼答案

    你的问题是隐藏的标志。我不知道为什么,但是一旦一个文件有了隐藏标志,Java就不能再写入它了

    我对它进行了测试,您可以删除该文件(在写入新文件之前),或者,如果您想在事务上更安全,可以写入另一个文件,并在关闭该文件后将其重命名为REPLACE_EXISTING。这两种方法都适用于隐藏文件

    顺便说一句:我不认为用Java序列化来存储这么简单的信息是个好主意。您最好使用文本格式

  2. # 2 楼答案

    在指定的文件/文件夹位置上,您的windows/linux文件读取/权限似乎有问题。在运行此应用程序之前,您需要确保您有足够的权限执行此操作。请记住,Java只做您要求它做的事情。您的错误消息非常清楚地指导您找到问题的原因

    通过执行此操作,您可以检查对该文件夹的write访问权限

    File f = new File("myfile.txt");
    if (f.canWrite)
    { 
         System.out.println("I can write here!!");
    }
    

    另一种方法是使用SecurityManger并检查是否为写入操作引发了异常:

    // Gets the application security manager
    SecurityManager sm = System.getSecurityManager();
    
    // Checks for write exceptions
    try
    {
         sm.checkRead(myFilePath_str); 
         sm.checkWrite(myFilePath_str);
    
    } catch(SecurityException se)
    
    {    // Who threw it?    
         se.printStackTrace(); 
    }
    

    另外,我刚刚注意到您正在从Runtime调用.exec()。您还可以使用checkExec()方法检查是否存在影响此操作的“不可见”标志

    希望这有帮助