Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File class questoin

 
haijun wang
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Grant Crofton
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic