没有确切的路径保存到桌面

时间:2015-07-16 07:43:13

标签: java

我想在桌面上保存文件。所以我有

FileOutputStream out =  new FileOutputStream(new File("C:\\path_to_Dekstop\\print.xls"));

它有效。但我想保存文件而不将确切的路径放到桌面上。我搜索了它,我发现了类似的问题,我提出了这个解决方案:

File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out =  new FileOutputStream(new File(pathToDesktop));

但我收到了错误

java.io.FileNotFoundException: C:\Users\nat\Desktop (Access is denied)

2 个答案:

答案 0 :(得分:2)

pathToDesktop表示Desktop的目录,您应提供要写入的文件名

FileOutputStream out = new FileOutputStream(new File(desktopDir, "File to be written to"));

"File to be written to"放在桌面上

答案 1 :(得分:0)

您无法直接将Desktop写为文件夹而不是file。您需要写入file。做点什么: -

File desktopDir = new File(System.getProperty("user.home"), "Desktop");
 System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
 String pathToDesktop = desktopDir.getPath();
 FileOutputStream out =  new FileOutputStream(new File(pathToDesktop+System.getProperty("file.separator")+"print.xls"));

这将写入print.xls中的Desktop