Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Can somebody help me on how to write data to file in java and how do i specify the location of the file as well. Thanks

FileOutputStream fo = new FileOutputStream(PATH_TO_OUTPUTFILE);
PrintStream ps = new PrintStream(fo);// write here your own code.
// with ps.println you can print a line to the file specified by PATH_TO_OUTPUTFILE.ps.close();
fo.close();

Thanks, in specifying path of the file do you use "c:/xxx/xxx/xxx" or "c:\xxx\xxx\xxx"
simply backslash or forwardslash
thanx

You can use forward slashes. For example, "d:/data/data.dat".
BTW: Don't forget to import java.io.* and to implement a try-catch statement around the code in my first reply: FileOutputStream can throw an Exception. So, the following code will do the job.
import java.io.*;
class test {
public static void main(String[] argv) {
try {
FileOutputStream fo = new FileOutputStream("d:/data/data.dat");
PrintStream ps = new PrintStream(fo);
ps.println("BLA");ps.close();
fo.close();
} catch (Exception e) {}
}
}Make sure that the directory "d:\data\" exists.

DEOS_NR1, Thanks for the suggestions. can you forward me your email add so that i can send you a copy of the particular section am having problem with so that you can look at.It does not seem to be working for me. Thanks

I have tried this method and it did not work. But i printed the error as u indicated in your previous mail and this is what it brought:
Java.Security.AccessControlException:access denied (java.io.FilePermission D:\data\bla
I figured it out that it could have something to do with my security permissions and have no clue how to go about it as am still new to java. Hope somebody can help.

in java you have to use two back slashes to create a directory path like so C:\\program\\sub1 and so on because a single slash has a meaning

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |