Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving files to a specific directory in Java?

Tags:

java

This is probably a silly question, but I'm pretty new to Java and I can't figure it out.
Basically, I'm trying to download some files from a website and I want to save them to a particular folder (rather than the default of the same folder that my Java file is located in). How can I do this?

I've been using FileReader, BufferedReader, BufferedInputStream, and FileOutputStream classes.

Thanks :)

like image 503
NSP Avatar asked Jun 16 '11 03:06

NSP


2 Answers

Java is pretty friendly with IO. Try something like this:

File file = new File("/some/absolute/path/myfile.ext");
OutputStream out = new FileOutputStream(file);
// Write your data
out.close();

Notes:

  • Your program needs permission to write to the directory.
  • If the first character of your path string is not /, it will be relative to your "current" directory
  • If you're writing text, you might find a BufferedWriter easier: BufferedWriter writer = new BufferedWriter(new FileWriter(file));. It has newLine() and write(String) methods
like image 95
Bohemian Avatar answered Oct 16 '22 11:10

Bohemian


When you insantiate your FileOutputStream you can pass an absolute path to the constructor. Like this:

FileOutputStream os = new FileOutputStream("/path/to/file.txt");
like image 33
Asaph Avatar answered Oct 16 '22 12:10

Asaph