Reading and Writing files (Java, Mac OSX)

Hello, I am "kind of" experienced with Java (read a few books, and took one course in highschool, and I fool around with it from time to time).

All of this however was on Windows XP, and all from the command line. Because I now have a Macbook Pro, I wish to start programming java on Mac OSX naturally. I've gotten over the shock and awe of using Xcode (I had never use a "package" before with multiple components), but I have come across a problem. I referenced one of my Java books on how to read from a .txt file (my intended program needs a database), but I've been trying for a few hours now, and I just can't seem to get it to work at all.

I want to read the entire file and save it as a String. I don't know if there is a different procedure on OSX than Windows, but here is what I am using:

(using the "premade model" with Xcode)


public String readPlease() {
String str = "";
try {
FileReader file = new FileReader("database.txt");
BufferedReader buff = new BufferedReader(file);
str = buff.readLine();
buff.close();
return str;
} catch (IOException e) {
return e.toString();
}
}



And it is returning:

java.io.FileNotFoundException: database.txt (No such file or directory)

The .java file and the .txt file are in the same folder (src) and I've tried it while its in "resources" and "bin" (where the .class files are).

Thank a lot 🙂

MacBook Pro, Mac OS X (10.5.7)

Posted on Jun 18, 2009 10:58 PM

Reply
3 replies

Jun 20, 2009 2:37 PM in response to JStock23

Hi

When you open a file in Java and don't specify a folder then it defaults to the same folder as your Jar file. The safest way around this is to always specify the complete file spec like this:
/Users/myUser/etc/etc/etc

If you're creating a production program then you can probably use a file chooser to allow the user to select the file.

If you want to read/write a file to the desktop then this works:

String desktop = System.getProperty ("user.home") + "/Desktop/";
File myFile = new File (desktop + "MyFile.txt");

A similar technique also works with /Documents/ too.

Good luck

Bob

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Reading and Writing files (Java, Mac OSX)

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.