我在 cwd 中的文件夹中创建文件时遇到一些问题 - 我最近从 Windows 切换到 Mac,并且文件的创建方式似乎存在一些细微的差异。
String servername = "123";
URL url = null;
URLConnection con = null;
int i;
try {
File parentFolder = new File("test2");
System.out.println("folder.exists():"+folder.exists()); // true
System.out.println("folder.isDirectory():"+folder.isDirectory()); // true
url = new URL("http://"+servername+".foo.com:8080/foo.bar");
con = url.openConnection();
File file = new File(parentFolder, servername+"the_file.out");
file.getParentFile().mkdirs();
BufferedInputStream bis = new BufferedInputStream(
con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
} catch (MalformedInputException malformedInputException) {
malformedInputException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
在此代码片段中,我从某个网页下载一个文件,并尝试将其保存在项目根目录中名为“test2”的文件夹中。
结果:
MyProject
test2
src
build
nbproject
123the_file.out // why doesn't it go into test2?
请注意,文件下载并写入正确,但同样,不在正确的目录中。
最佳答案
替换
new FileOutputStream(file.getName()));
与
new FileOutputStream(file);
您的file
对象包含文件的文件夹和名称。您需要将整个文件对象传递给 FileOutputStream。您的编码方式仅传递名称字符串 123the_file.out
,因此 FileOutputStream 将其解释为相对于您的 cwd
关于java - Java 相对路径文件创建中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613646/