A Guide To Advanced Java: Advj-Lab3
A Guide To Advanced Java: Advj-Lab3
Session Objectives
In this session, you will be practicing with InputStream class and its subclasses OutputStream class and its subclasses File class Buffered Streams Serialization
public class ReadFile { public static void main(String[] args) { // Create a file object File file = new File("D:\\test.txt"); try { // Open file to read BufferedReader br = new BufferedReader(new FileReader(file)); String data = ""; while( (data = br.readLine())!=null ) { // Display a string line System.out.println(data); } } br.close();
AdvJ-Lab3- Java IO
catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } }
Questions: - How to copy data of a file to another file? Hint: using BufferedWriter. 2. Listing the contents of a directory (in a file sytem). Copy the code, compile and run the program.
import java.io.File; public class Dir { static void listPath(File path) { // get all files (or directories) in File path File[] files = path.listFiles(); for (int i = 0, i < files.length; i++) { System.out.println(files[i].toString()); } } public static void main(String args[]) { listPath(new File("C:\\WINDOWS")); } }
Questions: - How to get all files in sub-directories of root Directory? Hint: using recursive method.
AdvJ-Lab3- Java IO
3. Exit Your choice: _ + Save to File: input information of several students and write that information into a text file, each student in a line (use tabs to separate the fields) + Read File: read and display information of students Exercise 3. Redo the Exercise 2 by using the classes ObjectInputStream and ObjectOutputStream. Exercise 4. Using BufferredInput/OutputStream to copy data from a file that has capacity exceed 10MB to another file. Exercise 5. Write a program to imitate the dir program. The path of directory is a parameter input from keyboard. List all files and sub directories with details as below figure.
AdvJ-Lab3- Java IO