This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes questions about several File methods. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "questions about several File methods." Watch "questions about several File methods." New topic
Author

questions about several File methods.

Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Hi everybody,
I had SEVERAL problems in the methods of File class and am hope you guys can help me out.
In the class below, junk is a directory which does exist, while f1 and f2 are directories in the local disk. For method getAbsolutePaty() only, the class will compile and has no problem in rum time. However,
1. after I add getCanonicalPath(), I got error message as "java.io.IOException must be caught, or it must be declared in throw clause�" no idea about what is going on.
2. For method list(), when I call f1.list(), I got some strange codes but not a list of directory as I expected. Never use it before, can somebody tell me how to use it?
3. for mkdir() method, I do not know how to use it actually, so just try it as it is. And I failed to create any directory in my disk. I hope someone could please explain how this method actually works.
Thanks a lot
import java.io.File;
public class Problems
{
public static void main(String s[]){
File junk=new File("///temp");//you can use whatever string, reasonable or not
File f1=new File("d:\\java2-certificate");
File f2=new File("D:\\java2-certificate","roundup.doc");

//boolean exists()
boolean temp=f1.exists(); //boolean exists()
System.out.println("existance of f1 is "+temp);
//return true in my CASE
temp=junk.exists();
System.out.println("existance of junk is "+temp);
//RETURN FALSE IN MY CASE
temp=f2.exists();
System.out.println("existance of f2 is "+temp);
//RETURN TRUE IN MY CASE
//String getAbsolutePath()
System.out.println("path of junk is "+junk.getAbsolutePath());
System.out.println("path of f1 is "+f1.getAbsolutePath());
System.out.println("path of f2 is "+f2.getAbsolutePath());

//String getCanonicalPath()
// System.out.println("path of junk is "+junk.getCanonicalPath());
// System.out.println("path of f1 is "+f1.getCanonicalPath());
// System.out.println("path of f2 is "+f2.getCanonicalPath());

//String[] list()
System.out.println("list of f1 is "+f1.list());
//boolean mkdir
File f7=new File("d:\\ttt/ttt.txt");
System.out.println("existance of f7 is "+f7.exists());
System.out.println("creation of f7 is "+f7.mkdir());
System.out.println("existance of f7 is "+f7.exists());
}
}
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

I can only help with your first question. If it says you must catch it or declare it in your throws clause, then you must do that. put the code that calls getCanonicPath() in a try block and then catch(IOException e){}


SCJP
Visit my download page
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Chris,
I have included a working example that shows you how to use the File methods. Remember that in Java terminology a File can be either a file or a directory. For the methods list() and mkdir() you need to specify a directory and not a file as you have done.

Enjoy,
Manfred.
Rosemol Thanjappan
Ranch Hand

Joined: Aug 08, 2000
Posts: 40
Hi Chris,
File objects can be created with any String.But when we come
across with operations involving real, files and directories
the path represented by the File object must be a valid path.
Other wise we won't get the results we expected.How the files and directories can be reached without knowing the correct path? it is not possible .
Example :

Yes , It will return "false" since the path is not valid.
Try to change the file object String of 'junk' to valid path of directory "temp".

3. for mkdir() method, I do not know how to use it actually, so just try it as it is. And I failed to create any directory in my disk. I hope someone could please explain how this method actually works.

This is same as the above case,also the String must be a directory name not a file name.

Here change the String of file object 'F7' to a valid directory path.
example : File f7=new File("d:\\ttt");

1. after I add getCanonicalPath(), I got error message as "java.io.IOException must be caught, or it must be declared in throw clause�" no idea about what is going on.

The signature of getCanonicalPath(), is
public String getCanonicalPath()throws IOException
So the method call must be declared in a try-catch block.


2. For method list(), when I call f1.list(), I got some strange codes but not a list of directory as I expected. Never use it before, can somebody tell me how to use it?

signature of File.list() is
public String[] list()
Returns an array of strings naming the files and directories in the directory
So

" f1.list() " Returns an array and what printed out is the HashCode value of that array.
To get the content of the array reurned by " f1.list() " try this

Hope this may help...
Rosemol
Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Hi,
Thanks a lot to all you guys. You are VERY helpful! I appreciate your time and patience.
Manfred's codes are very self-explannatory, but I catch more questions from it. How many ways do we have to describe the path in Dos/window and UNIX for an "existed file"?
In my case, I used
File f6=new File("d:\\java2-certificate/roundup.doc");
(d:\\java2-certificate\roundup.doc does not work)
in your case, you use
D:\\TEMP\\firstFile.doc
Any more? And how about UNIX?
In addition, for Canonical method, I cannot see the difference in the use between it and getabsolutePath() in those examples, could you please give me another example?
Rosemol's code remind me to go to sun's API to check the original signature of all methods. Rosemol is right about the signature of getCanonicalPath(). That is my problem. It is really a trap for an unexperienced programmer as me and it is too bad that RHE does not indicate it (P379).
Another question about signature as throws IOException:
Can I say that I have to use try catch block in whatever method with signature of throws whateverException in programming, otherwise, compiler will complain?
It seems true in this case, but when I write another program for RandomAccessFile practice, I can construct a RAF without using catch block (see example below). THough it is a constructor but this constructor has a signature of throw exception, too (http://java.sun.com/j2se/1.3/docs/api/index.html). I am a little confused.
Thanks again for your help
import java.io.*;
public class RandomPractice
{
//constructors
//RandomAccessFile(String File, String mode); RandomAccessFile(File file, String mode)
public static void main(String[] afg) throws IOException {
File f=new File("d:\\java2-certificate/access2.doc");
// RandomAccessFile r2=new RandomAccessFile("d:\\java2-certificate/access2.doc", "rw");
// RandomAccessFile r3=new RandomAccessFile(f, "rrrr");//this has no compiling errors but running time error
RandomAccessFile r4=new RandomAccessFile(f, "rw");
r4.writeBytes("test-writeByte");
}
}
Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
BTW, I try to construct one RandomAccessFile outside main method as below, but get error message as "Type expected". Could anyone explain to me why? Thanks
try{
RandomAccessFile r1=new RandomAccessFile("\\\temp", "rw");
}catch(FileNotFoundException e){}
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Chris,
As far as specifying a directory in any Java method you can (and probably should) just use a single forward slash ('/').
As for your latest problem. You should remember that in Java you can only place member variables, static blocks, methods, or other classes inside any class. You are trying to place a statement inside a class that is not one of the above. The closest the compiler can come is member variables. For member variables, you must specify: <type> var = ...
It would have worked had you done the following:
RandomAccessFile raf = new RandomAccessFile(...);
Manfred.
Zheng Huang
Ranch Hand

Joined: Dec 20, 2000
Posts: 49
Put your statement into {}. It will compile.
Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Hi Manfred,
Thanks for the reply. In fact, the codes below will not compile, that is why I put it in a try block after a lot frustration (see my attached codes with comment line please).
--It would have worked had you done the following:
--RandomAccessFile raf = new RandomAccessFile(...);

For Zheng,
--Put your statement into {}. It will compile.
Didn't get you. could u plz put the codes here? Thanks.
import java.io.*;
public class RandomPractice
{
//constructors
//RandomAccessFile(String File, String mode) throws FileNotFoundException;
RandomAccessFile r1=new RandomAccessFile("d:\\temp", "rw");
//error message: Exception java.io.FileNotFound cannot be thrown in initilizer
//the codes below is fine in compiling
public static void main(String[] afg) throws IOException {
File f=new File("d:\\java2-certificate/access2.doc");
// RandomAccessFile r2=new RandomAccessFile("d:\\java2-certificate/access2.doc", "rw");
// RandomAccessFile r3=new RandomAccessFile(f, "rrrr");//this has no compiling errors but running time error
RandomAccessFile r4=new RandomAccessFile(f, "rw");
r4.writeBytes("test-writeByte");
}
}
Rosemol Thanjappan
Ranch Hand

Joined: Aug 08, 2000
Posts: 40
Hi Chris,
Is the run time " IllegalArguementException " bothers you.
API says :
if the mode argument is not equal to "r" or to "rw" an IllegalArguementException is thrown.
Rosemol.
Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
No.Rosemol.
The problem is as my codes:
public class RandomPractice
{
RandomAccessFile r1=new RandomAccessFile("d:\\temp", "rw");
//error message: Exception java.io.FileNotFound cannot be thrown in initilizer
....
Rosemol Thanjappan
Ranch Hand

Joined: Aug 08, 2000
Posts: 40
Hi Chris,
You cannot use Member initialization with the declaration has exception problems:
- cannot call methods that throw a checked exception.
- If you need to deal with errors you can put the initialization code along with try/catch statements.
case 1: for instance fields
a) either in a constructor ()or
b) instance (non-static) initialization blocks
case 2: for static fields.
in a static initialization block

In this code the constructor
RandomAccessFile(....) thows FileNotFoundException.
So you have to put the code in try-catch block.
Since it is an initializer statement rather than a code block we can't use the try-catch block here.
Try the alternatives.
Put it in a instance (non-static) initialization blocks with try-catch .

Example :

Rosemol
Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Thanks a lot, Rosemol.
Have a good night
Ben
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: questions about several File methods.
 
Similar Threads
File Input/Output
files are not beened deleted and renamed
File Class
Question about static
I/O- Ranchers Attention Please