通常,当您的应用程序应该写入文件时,它必须在具有写入权限的地方执行此操作。您唯一可以确定的地方(在大多数情况下)允许您的应用程序拥有此类访问权限的是用户主目录。您可能已经注意到,其他基于Java的应用程序通常会在您的个人文件夹中创建一个名为".some-application"
的目录(您的情况为"C:\Users\Rohan Kandwal"
)。原因(其中之一)为什么他们这样做是写入权限。
你应该这样做,忘记使用Class.getResourceAsStream(...)
作为可写文件。您可以通过System.getProperty("user.home")
获得到您的主目录的路径。
请注意,在您的示例中使用Class.getResourceAsStream(...)
的原因是从build
目录获取文件是因为您正在IDE内运行它。如果你在IDE之外运行它,这个路径将会改变。这是因为类文件(xmlhandler.class
)的路径很可能会更改,并且Class.getResourceAsStream(...)
依靠它来查找资源。
另请注意,在部署应用程序时,您的src
目录很可能不存在。即使这样做,也无法知道您的用户是否将其部署在具有写权限的位置。所以你试图做的事情没有多大意义。
Edit01
这是你怎么会做你想做的一个例子。这将为您的应用程序创建一个主目录,您可以按照自己的意愿书写文件。如果您要在应用程序运行之间保留的文件不存在,它将被创建并填充您的资源文件的内容。请注意,这只是一个例子。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ConfigDir {
private static final String APP_DIR = ".myappdir";
private static final String FILE_NAME = "shutdownscheduler.xml";
private File fillFileFromTemplate(InputStream template, File file) throws FileNotFoundException, IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = template.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
return file;
} catch (FileNotFoundException ex) {
throw ex;
} finally {
if (out != null) {
out.close();
}
}
}
public static void main(String[] argv) throws IOException {
String userdir = System.getProperty("user.home"); // user home directory
// OR if you know that your program will run from a directory that has write access
// String userdir = System.getProperty("user.dir"); // working directory
if (!userdir.endsWith(System.getProperty("file.separator"))) {
userdir += System.getProperty("file.separator");
}
String myAppDir = userdir + APP_DIR;
File myAppDirFile = new File(myAppDir);
myAppDirFile.mkdirs(); // create all dirs if they do not exist
String myXML = myAppDir + System.getProperty("file.separator") + FILE_NAME;
File myXMLFile = new File(myXML); // this is just a descriptor
ConfigDir cd = new ConfigDir();
if (!myXMLFile.exists()) {
// if the file does not exist, create one based on your template
// replace "ConfigDir" with a class that has your xml next to it in src dir
InputStream template = ConfigDir.class.getResourceAsStream(FILE_NAME);
cd.fillFileFromTemplate(template, myXMLFile);
}
// use myXMLFile java.io.File instance for read/write from now on
/*
DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder=documentbuilderfactory.newDocumentBuilder();
Document document=(Document)documentbuilder.parse(myXMLFile);
document.getDocumentElement();
...
*/
}
}
见[http://stackoverflow.com/questions/2797367/write-to-a-file-stream-returned-from-getresourceasstream](http://stackoverflow.com/questions/2797367/write -to-a-file-stream-returned-from-getresourceasstream) – predi