2. Creating a File object does not mean creation of any file or directory, and then when does the creation of physical file take place?
A: The answer is it depends...
The physical file might be created 10 years ago by one of your long gone colleagues , or will be created on the next step of running when your program tries to write something onto the not-yet-exist file by using FileOutputStream or FileWriter.
You can also call createNewFile() of the java.io.File object to create a new, empty file named by its abstract pathname if and only if a file with this name does not yet exist.
The file might never be created since the program does not have write permission (of java.io.FilePermission) in that specified directory.
The file might never be created simply because the program never try to do anything on it, absentminded programmer, of course.
The java.io.File object might just represent a directory, which might not be a file at all.
Read The Java Tutorial It is free. Read javadoc, and compare the exception thrown by File and FileWriter constructors will help as well.
3. Is it possible to change directory by using File object?
A: No, You cannot change the directory by using a file object.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
However, you can use one File object to find the directory you want, and then create another File object for the directory you want to go to.
4. How to create a new directory by using File object?
A: Using class File method mkdir() or mkdirs(). See code here:
// MakeDir.java
import java.io.*;
public class MakeDir {
public static void main(String args[]){
// make sure sub-directory "mmm" does not exist
File dir=new File("mmm");
System.out.println(dir.mkdir());// true
// make sure at least two of "hhh\\lll\\nnn" does not exist
File multidir=new File("hhh\\lll\\nnn");
System.out.println(multidir.mkdir()); // false
System.out.println(multidir.mkdirs()); // true
// make sure at least two of "..\\ccc\\ddd\\eee" does not exist
File updir=new File("..\\ccc\\ddd\\eee");
System.out.println(updir.mkdir()); // false
System.out.println(updir.mkdirs()); // true
// If you run the code second time,
// the result will be different. Why?
}
}
5. What are the differences between FileInputStream/FileOutputStream and RandomAccessFile? Do you have a good example on it?
A: Remember never mixing RandomAccessFile with Streams!!! RandomAccessFile class is more or less a legacy from c language, the Stream concepts/C++ were not invented then.
This example deals with File, FileInputStream, DataOutputStream, RandomAccessFile. Play with it; try to understand every bit of the output. IOTest.java
6. What are the difference between File.getAbsolutePath() and File.getCanonicalPath()? Can they return different result?
A: Find your answer by reading this:
http://java.sun.com/j2se/1.3/docs/api/java/io/File.html
Yes, they can return different results! See the following example. Pay attention to the comments.
import java.io.*;
public class T
{
static void testPath(){
File f1 = new File("/home/jc/../rz/rz.zip"); // file does not exist
File f2 = new File("T.class"); // file in rz dir under /home/rzhang
// no try/catch block needed
// return "/home/jc/../rz/rz.zip" always
System.out.println("Absolute path for f1: " + f1.getAbsolutePath());
// return "/home/rzhang/rz/T.class"
System.out.println("Absolute path for f2: " + f2.getAbsolutePath());
try {
// not compilable if neither try/catch block nor throws present
// return "/home/rz/rz.zip"
System.out.println("Canonical path for f1: " + f1.getCanonicalPath());
// return "/home/rzhang/rz/T.class"
System.out.println("Canonical path for f2: " + f2.getCanonicalPath());
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public static void main(String[] args){
T.testPath();
}
}
7. Which one of the following will create an InputStreamReader correctly?
-
new InputStreamReader(new FileInputStream("data"));
-
new InputStreamReader(new FileReader("data"));
-
new InputStreamReader(new BufferedReader("data"));
-
new InputStreamReader("data");
-
new InputStreamReader(System.in);
A:
The leagal constructors for InputStreamReader are
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String enc)
-
If you compile this line without a try/catch block, you will get a compile error: Exception java.io.FileNotFoundException must be caught, or it must be declared in the throws clause of this method.
How to do it correctly?try {
new InputStreamReader(new FileInputStream("data"));
}
catch (java.io.FileNotFoundException fnfe) {
}Answer: If they let you choose one, choose e. If they let you choose two, choose a and e.
-
Error #1: FileReader is not an InputStream.
Error #2: The same problems as a), Exception java.io.FileNotFoundException must be caught -
Error #1: BufferedReader is not an InputStream. Error #2: There is no contructor of BufferedReader to take string as argument.
-
String "data" is not an InputStream.
-
Correct, since System.in is an InputStream.
8. Why only read() methods in ByteArrayInputStream does not throw IOException?
A: You are right, read() methods of all other InputStreams throw IOException except ByteArrayInputStream.
This is because the entire byte array is in memory; there is no circumstance in which an IOException is possible.
However, close() and reset() methods of ByteArrayInputStream still can throw IOException.
9. How does InputStream.read() method work? Can you give me some sample code?
A:Here is the sample code; the explanation is in the comments. Make sure you compile it, run it, and try to understand it.
// TestRead.java
import java.io.*;
public class TestRead {
public static void main(String argv[]) {
try {
byte[] bary = new byte[]{-1, 0, 12, 23, 56, 98, 23, 127, -128};
ByteArrayInputStream bais = new ByteArrayInputStream(bary);
System.out.print("{ ");
while (test(bais)){
System.out.print(", ");
}
System.out.println(" }");
// output: { 255, 0, 12, 23, 56, 98, 23, 127, 128, -1 }
// Notice 2 negative byte value becomes positive
// -1 is added to the end to signal EOF.
}
catch (IOException e) {
System.out.println(e);
}
}
public static boolean test(InputStream is) throws IOException {
// Read one byte at a time and
// put it at the lower order byte of an int
// That is why the int value will be always positive
// unless EOF, which will be -1
int value = is.read();
System.out.print(value);
// return true as long as value is not -1
return value == (value & 0xff);
}
}
10. How to read data from socket? What is the correct selection for the question?
A socket object (s) has been created and connected to a standard Internet service
on a remote network server.
Which of the following gives suitable means for reading ASCII data,
one line at a time from the socket?
A. s.getInputStream();
B. new DataInputStream(s.getInputStream());
C. new ByteArrayInputStream(s.getInputStream());
D. new BufferedReader(new InputStreamReader(s.getInputStream()));
E. new BufferedReader(new InputStreamReader(s.getInputStream()),"8859-1");
A:
A. InputStream does not readLine()
B. DataInputStream.reaLine() deprecated
C. ByteArrayInputStream does not readLine()
D. the only correct answer.
E. encoding put in the wrong place. The correct way is
new BufferedReader(new InputStreamReader(s.getInputStream(), "8859-1"));
See sample from the Sun: Reading from and Writing to a Socket
11.How to use ObjectOutputStream/ObjectInputStream?
A:
A sample code here, which writes to ObjectOutputStream, and reads it back from ObjectInputStream. The program not only deals with instance object, but also Class object. In addition, it uses reflection to analyze how it works.
Find it at TestSerialization.java Pretty heavy i/o, serialization, reflection, transient/static stuff, if it is too over your head, skip it.
12. How to compare two (binary/not) files to see if they are identical?
A:
1) Open 2 streams
2) Compare their length first, if not the same, done
3) If the same lengths, then compare byte to byte, until you find anything not the same, or end-of-file
4) You get your answer
13. When I use the following code to write to a file, why the file has no data in it?
// WriteFile.java
import java.io.*;
public class WriteFile {
public static void main(String[]args)throws Exception {
FileOutputStream fos = new FileOutputStream("out.txt");
PrintWriter pw = new PrintWriter(fos);
pw.print(true);
pw.println("short content file");
}
}
A:
When you open out.txt, it is an empty file, correct. Try to write a lot of text on to the file, and then you get something back, but not all of them.
Why? The reason is for efficiency, the JVM or OS tries to buffer the data to reduce the hit of hard disk or other media. If you do not flush and close, the data might be lost.
I remember when I was coding in Pascal (C?), I had exact the same problem. I learned a lesson that always closing you file or stream after finishing read/write to it.
If you change you code to the forlowing, everything will be ok!
// WriteFile.java
import java.io.*;
public class WriteFile {
public static void main(String[]args)throws Exception {
FileOutputStream fos = new FileOutputStream("out.txt");
PrintWriter pw = new PrintWriter(fos);
pw.print(true);
pw.println("short content file");
pw.close();
fos.close();
}
}
No comments:
Post a Comment