gpt4 book ai didi

java - 使用Java的File类以及如何获得正确的访问权限来创建文件

转载 作者:行者123 更新时间:2023-12-01 22:03:26 25 4
gpt4 key购买 nike

下面是我编写的房屋清洁函数的代码,该函数应该检查文件是否存在,如果不存在,则创建文件并向其中添加一些数据。但是,当我使用 file.canRead()file.canWrite() 检查我是否具有读写权限时,这些权限在检查时都会返回 false,但程序应该具有访问权限到指定的文件路径。

public void HouseCleaning()
{
//inform the user that the file is not available
System.out.println("According the the checks we have run, the current system you are on we do not have the required files set up");
System.out.println("...");
//create info.txt
try
{
File file = new File("C:\\GameCounter\\info.txt");
System.out.println(file.canRead());
System.out.println(file.canWrite());
if(file.canRead() && file.canWrite())
{

//then we can create the file
System.out.println("we can do this");
if(!file.exists())
{
//file does not exist
if(file.createNewFile())
{
//file has been created
System.out.println("File has been successfully created!");
PrintWriter writer = new PrintWriter("C:\\GameCounter\\info.txt", "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
}
else
{
//file has not been created!
System.out.println("for some reason the file cannot be created!");
}

}
else
{
//file must already exist? so check for other required ones!
}
}
else
{
System.out.println("we require extre permissions!");
}





}
catch(Exception e)
{
//error has been thrown
System.out.println(e);

}
}

所以我的问题首先是,理论上如果下面的代码正确,那么它就是硬盘本身的权限?如果代码不正确,请纠正我。非常感谢您对此提供的任何帮助。

最佳答案

我建议您更改程序并利用 Java 异常处理提供的优势。

private final static String COUNTER = "C:\\GameCounter\\info.txt";

public static void main(String[] args) {
File file = new File(COUNTER);
if (!file.exists()) {
try {
PrintWriter writer = new PrintWriter(COUNTER, "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

/// ... more to come
}

这要短得多,而且无论如何你都必须处理异常情况。如果文件无法写入(在我的测试中,我只是创建了它并分配了只读属性),您将收到相应的异常:

java.io.FileNotFoundException: C:\GameCounter\info.txt (Access denied)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at java.io.PrintWriter.<init>(PrintWriter.java:192)
at java.io.PrintWriter.<init>(PrintWriter.java:232)
at xyz.main(xyz.java:12)

在我的示例中,我仅将异常转储到屏幕上。在现实生活场景中,您需要对异常使用react,并且可能重新抛出您自己定义的异常。

关于java - 使用Java的File类以及如何获得正确的访问权限来创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33296801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com