我想在具有Java的计算机的目录中创建一个文件 [英] I want to create a file in a directory in computers with Java
问题描述
我正在玩游戏,该游戏需要在用户帐户的AppData文件夹中创建一个特定的目录。现在的问题是,由于每个用户不一样,我无法确切地知道放在哪里。这是在Windows上的方式。我想知道我是否应该写一些特殊的东西或者... ...
文件文件=新建文件(C:\\\ \\Users\\%USER%\\AppData\\Roaming\\ [gameName]);
是否有一些特殊的名称,我必须给%USER%(我刚刚使用作为一个例子),还是有其他的东西我要做?
你可以使用APPDATA环境变量,通常是 C:\Users\username\AppData\Roaming
您可以使用System.getenv()函数获取它:
String appData = System.getenv()。get(APPDATA);
编辑: / p>
看这个例子(创建一个目录myGame并在这个目录中创建一个文件myGameFile)。
代码很糟糕,但这只是给你一个如何工作的想法。
String gameFolderPath,gameFilePath;
gameFolderPath = System.getenv()。get(APPDATA)+\\myGame;
gameFilePath = gameFolderPath +\\\mymyGameFile;
文件gameFolder = new File(gameFolderPath);
if(!gameFolder.exists()){
//文件夹不存在。创建它
如果(gameFolder.mkdir()){
//文件夹创建
文件gameFile =新文件(gameFilePath);
if(!gameFile.exists()){
//文件不存在,创建它
try {
if(gameFile.createNewFile()){
//在%APPDATA%\myGame中创建mGameFile!
}
else {
//错误
}
} catch(IOException ex){
//处理这里的异常
}
}
else {
//文件存在
}
}
else {
//错误
}
}
else {
//文件夹存在
}
I'm making a game, and that game requires a certain directory to be made in the AppData folder of the user's account. Now the problem is, I can't exactly know where to put it, as every user is different. This is on windows by the way. I want to know if I should write something special or...
File file = new File("C:\\Users\\%USER%\\AppData\\Roaming\\[gameName]");
Is there some special name that I have to give the "%USER%" (I just used that as an example), or is there something else I gotta do?
You can use the APPDATA environment variable which is usually "C:\Users\username\AppData\Roaming"
And you can get it using System.getenv() function :
String appData = System.getenv().get("APPDATA");
EDIT :
Look at this example (create a directory "myGame" and create a file "myGameFile" into this directory). The code is awful but it's just to give you an idea of how it works.
String gameFolderPath, gameFilePath;
gameFolderPath = System.getenv().get("APPDATA") + "\\myGame";
gameFilePath = gameFolderPath + "\\myGameFile";
File gameFolder = new File(gameFolderPath);
if (!gameFolder.exists()) {
// Folder doesn't exist. Create it
if (gameFolder.mkdir()) {
// Folder created
File gameFile = new File(gameFilePath);
if (!gameFile.exists()) {
// File doesn't exists, create it
try {
if (gameFile.createNewFile()) {
// mGameFile created in %APPDATA%\myGame !
}
else {
// Error
}
} catch (IOException ex) {
// Handle exceptions here
}
}
else {
// File exists
}
}
else {
// Error
}
}
else {
// Folder exists
}
这篇关于我想在具有Java的计算机的目录中创建一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!