Sunteți pe pagina 1din 32

SSK 3101 COMPUTER PROGRAMMING II

Topic 8 File Management


Assoc. Prof. Dr. Nurfadhlina Mohd Sharef
Department of Computer Science
Faculty of Computer Science and Information Technology
University Putra of Malaysia

Room No: C2-08


Learning Objectives
• At the end of this chapter, you will be able to:
• Construct and Demonstrate input/output class in solving
programming problems (P4, A3)

2 Topic 8 Recursion SSK3101 Computer Programming II


Chapter 8 Outline

 8. File Management
This chapter will cover the following topics:
8.1 Stream
8.2 File Class

3 Topic 8 Recursion SSK3101 Computer Programming II


8.1 Stream
Stream
 Is an object that allows for the flow of data between
your program and some I/O device or some file.
 Input Stream
 The flow is into the program
 Example: System.in
Scanner scan = new Scanner (System.in);
 Output Stream
 The flow is out of the program
 Example: System.out
 System.out.println();

5 Topic 8 Recursion SSK3101 Computer Programming II


8.2 File Class
The File Class

 The File class is intended to provide an abstraction


that deals with most of the machine-dependent
complexities of files and path names in a machine-
independent fashion.
 The filename is a string.
 The File class is a wrapper class for the file name
and its directory path.

7 Topic 8 Recursion SSK3101 Computer Programming II


The File class
 Create File object
 Syntax:

java.io.File fileObject = new java.io.File(filename);


 Example:

java.io.File file = new java.io.File(“score.txt”);


 Check whether file already created or not
 Syntax:

file.exists()
 Example:

while (file.exists()) {
}
 Delete the file (will return true if the deletion succeed)
if (file.delete())
System.out.println(“File deleted”);
8 Topic 8 Recursion SSK3101 Computer Programming II
Obtaining file
properties and
manipulating file

9 Topic 8 Recursion SSK3101 Computer Programming II


Example: Using the File Class
Objective:

Write a program that demonstrates how to create files


in a platform-independent way and use the methods in
the File class to obtain their properties. Figure below
shows a sample run of the program on Windows, and
a sample run on Unix.

10 Topic 8 Recursion SSK3101 Computer Programming II


1. public class TestFileClass {
2. public static void main(String[] args) {
3. java.io.File file = new java.io.File("image/us.gif");
4. System.out.println("Does it exist? " + file.exists());
5. System.out.println("Can it be read? " + file.canRead());
6. System.out.println("Can it be written? " + file.canWrite());
7. System.out.println("Is it a directory? " + file.isDirectory());
8. System.out.println("Is it a file? " + file.isFile());
9. System.out.println("Is it absolute? " + file.isAbsolute());
10. System.out.println("Is it hidden? " + file.isHidden());
11. System.out.println("Absolute path is " +file.getAbsolutePath());
12. System.out.println("Last modified on " +
13. new java.util.Date(file.lastModified()));
14. }
15. }

11 Topic 8 Recursion SSK3101 Computer Programming II


Text I/O
 A File object encapsulates the properties of a file or a path,
but does not contain the methods for reading/writing data
from/to a file.
 In order to perform I/O, you need to create objects using
appropriate Java I/O classes.
 The objects contain the methods for reading/writing data
from/to a file.
 This section introduces how to read/write strings and
numeric values from/to a text file using the Scanner and
PrintWriter classes.

12 Topic 8 Recursion SSK3101 Computer Programming II


Writing to a Text File
 Class PrintWriter is the preferred stream class for writing to a
text file.
 PrinterWrite has methods print and println.
 Create a stream to associate the output stream with the file
java.io.File file = new java.io.File(“score.txt”);
PrintWriter output = new PrintWriter(file);

13 Topic 8 Recursion SSK3101 Computer Programming II


Writing Data Using PrintWriter

14 Topic 8 Recursion SSK3101 Computer Programming II


1. import java.io.*;
2. import java.util.*;
3. public class WriteDataToFile{
4. public static void main(String[] args) throws Exception{
5. String fname="phonebook.txt";
6. File file = new File(fname);
7. if(file.exists()){
8. System.out.println("File "+fname+" already exists");
9. System.exit(0);
10. }
11. // Create a file
12. PrintWriter output=new PrintWriter(file);
13. // Write formatted output to the file
14. output.printf("%-15s %-15s\n","Name","Phone Number");
15. output.printf("%-15s %-15s\n","Ah Chong","012-2121669");
16. output.printf("%-15s %-15s\n","Ahmad Jais","016-21634340");
17. output.close();
18. }
19. }

15 Topic 8 Recursion SSK3101 Computer Programming II


16 Topic 8 Recursion SSK3101 Computer Programming II
public class WriteData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");

if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
output.close();
}
}
17 Topic 8 Recursion SSK3101 Computer Programming II
Reading from a Text File
 Two common stream classes
 Scanner

 BufferedReader

 Scanner
 Replace the argument System.in with suitable stream that is
connected to the text file.
Scanner input = new Scanner (file);
Or
Scanner input = new Scanner (new
java.io.File(“scores.txt”));

18 Topic 8 Recursion SSK3101 Computer Programming II


 Throw FileNotFoundException if the file is failed to open. (you
need to import java.io.FileNotFoundException)
Scanner input = null;
try {
input = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println(file + " not found");
System.exit(0);
}

19 Topic 8 Recursion SSK3101 Computer Programming II


Reading Data Using Scanner

20 Topic 8 Recursion SSK3101 Computer Programming II


1. import java.io.*;
2. import java.util.*;
3. import java.util.Scanner.*;
4. public class ReadData{
5. public static void main(String[] args) throws Exception{
6. String fname="phonebook.dat";
7. // Create a File instance
8. File file = new File(fname);
9. if(!file.exists()){
10. System.out.println("File "+fname+" not exists");
11. System.exit(0);
12. }
13. // Create a file
14. Scanner input=new Scanner(file);
15. input.useDelimiter(":");
16. // Read data from a file
17. while(input.hasNext()){
18. String name = input.next();
19. String phone= input.next();
20. System.out.printf("%-15s %-15s",name,phone);
21. }
22. input.close();
23. }
24. }

21 Topic 8 Recursion SSK3101 Computer Programming II


22 Topic 8 Recursion SSK3101 Computer Programming II
Example: Replacing Text
Write a class named ReplaceText that replaces a string in
a text file with a new string. The filename and strings are
passed as command-line arguments as follows:
java ReplaceText sourceFile targetFile oldString
newString
For example, invoking
java ReplaceText source.dat target.dat file File
 replaces all the occurrences of StringBuilder by

StringBuffer in FormatString.java and saves the new file


in t.txt.

23 Topic 8 Recursion SSK3101 Computer Programming II


1. import java.io.*;
2. import java.util.*;
3. public class ReplaceText {
4. public static void main(String[] args) throws Exception {
5. if (args.length != 4) { // Check command line parameter usage
6. System.out.println("Usage: java ReplaceText sourceFile targetFile oldStr newStr");
7. System.exit(0);
8. }
9. File sourceFile = new File(args[0]); // Check if source file exists
10. if (!sourceFile.exists()) {
11. System.out.println("Source file " + args[0] + " does not exist");
12. System.exit(0);
13. }
14. File targetFile = new File(args[1]); // Check if target file exists
15. if (targetFile.exists()) {
16. System.out.println("Target file " + args[1] + " already exists");
17. System.exit(0);
18. }
19. Scanner input = new Scanner(sourceFile); // Create input and output files
20. PrintWriter output = new PrintWriter(targetFile);
21. while (input.hasNext()) {
22. String s1 = input.nextLine();
23. String s2 = s1.replaceAll(args[2], args[3]); // Search all String args[2] in s1 and then replace with args[3]
24. output.println(s2); // save on target file
25. }
26. input.close();
27. output.close();
28. }
29. }

24 Topic 8 Recursion SSK3101 Computer Programming II


Example: GUI – File Dialogs
1. import java.util.Scanner;
2. import javax.swing.JFileChooser;
3. import java.io.*;
4. public class ReadFile{
5. public static void main(String[] args) throws Exception{
6. JFileChooser fileChooser = new JFileChooser();
7. if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
8. //Get the selected file
9. File file = fileChooser.getSelectedFile();
10. Scanner input = new Scanner(file); // Create a Scanner for the file
11. while(input.hasNext()){// Read text from the file
12. System.out.println(input.nextLine());
13. }
14. // Close the file
15. input.close();
16. }
17. else{
18. System.out.println("No file selected");
19. }
20. }
21. }

25 Topic 8 Recursion SSK3101 Computer Programming II


26 Topic 8 Recursion SSK3101 Computer Programming II
Reading a Text File Using BufferedReader

 Similar to Scanner and was introduced before Scanner


came out.
 The class FileReader is used to convert the file name to
an object that can be associated to the BufferedReader.
FileReader file = new FileReader(“scores.txt”):
BufferedReader inFile = new BufferedReader(file);

Note: make sure to import java.io.*; at the beginning of the


program.

27 Topic 8 Recursion SSK3101 Computer Programming II


Create BufferedReader from FileReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class testBufferReader{
public static void main(String[] args) throws IOException{
FileReader file = new FileReader("scores.txt");
BufferedReader infile = new BufferedReader(file);
String s = new String();
while((s = infile.readLine()) != null){
System.out.println(s);
}
infile.close();
}
Scores.txt
} John T Smith 90
Eric K Jones 85

28 Topic 8 Recursion SSK3101 Computer Programming II


Create BufferedReader from InputStreamReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainClass {


public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a line:");
System.out.println(stdin.readLine());
}
}

29 Topic 8 Recursion SSK3101 Computer Programming II


Exercise
 Write a complete (although simple) Java program that ask
the user to input a file name and create the file. Then, tests
whether the file is already exists.
 Re-write the above program where if the file is already
exists, asks user whether want to delete the file.
 Write a program that read student’s score from an input file.
This file contains student’s matric number, scores for first
test (20%), second test (20%), lab assignment (20%) and
final exam (40%). Your program need to find the total
scores for each student and grade based on the total scores.
Write in the output file the student matric number, total
score and grade.

30 Topic 8 Recursion SSK3101 Computer Programming II


Summary
End of Chapter 8

S-ar putea să vă placă și