Forums Register Login

File class questoin

+Pie Number of slices to send: Send
Hi My friends:
I am trying to use JAVA file class to create a directory and file using following code in windows ME environment. The compile is ok, but it looks like both directory and file were not created. Could you please tell me the reason.
Thank you
Haijun
import java.io.*;
public class TryFile
{
public static void main (String [ ] args)
{
File myDir = new File ("D:/newFile/newFile/try");
System.out.println (myDir + (myDir.isDirectory()? " is" :" is not") + " a directory.");
File myFile = new File ("File.java");
System.out.println ( myFile + (myFile.exists() ? " does" : " does not" ) + "exist");
System.out.println ("you can" + (myFile.canRead() ? " " : " not ") + "read " + myFile);
System.out.println("you can" + (myFile.canWrite()? " ": " not ") + "write" + myFile );
return;
}
}
+Pie Number of slices to send: Send
Hi,
The reason is simple: Java File class doesn't create any files EVER!!
You must use other io to create files. For example:
RandomAccessFile raf = new RandomAccessFile( "newFile", "rw" );
creates a file named "newFile" and opens it for reading and writing. Another example:
FileInputStream fis = new FileInputStream( "newFile" );
creates a file named "newFile" and opens it for reading. Yet another example:
FileOutputStream fos = new FileOutputStream( "newFile" );
creates a file named "newFile" and opens it for writing.
Regards,
Manfred.
+Pie Number of slices to send: Send
Yeah, the File class is a bit deceptively named - it's just the name of a file/directory, nothing more. It's useful as it lets you find out / set stuff about the file with the name stored in the File object, but it's not actually a file as in a collection of bits on the HD.
I think you can actually create a file with the createNewFile() or createTempFile() methods of File, like

but I've never actually tried it.
permaculture is largely about replacing oil with people. And one tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1084 times.
Similar Threads
Select directory with JFileChooser
working with files and directories
reding in csv file
File Permissions
I/O and Files
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:55:48.