I’m having some issues creating a file within a folder in the cwd – I’ve recently switched from windows to mac, and it appears as though there are some subtle differences in how files are to be created.
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();
}
In this code snippet, I’m downloading a file from some webpage and trying to save it in a folder called ‘test2’ which is in my project root.
The result:
MyProject
test2
src
build
nbproject
123the_file.out // why doesn't it go into test2?
As a note, the file downloads and writes correctly, but again, not in the right dir.
Replace
with
Your
fileobject contains both the folder and name of the file. You need to pass the entire file object to FileOutputStream. The way you have it coded you are only passing the name string123the_file.outso FileOutputStream interprets it as relative to your cwd