File Class
public class TestFileClass {
public static void main(String[] args) {
java.io.File file = new java.io.File("image/us.gif");
System.out.println("Does it exist? " + file.exists());
System.out.println("Can it be read? " + file.canRead());
System.out.println("Can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it hidden? " + file.isHidden());
System.out.println("Absolute path is " +
file.getAbsolutePath());
System.out.println("Last modified on " +
new java.util.Date(file.lastModified()));
}
}
Text-IO
This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and PrintWriter classes.
PrintWriter
import java.io.*;
public class WriteData {
public static void main(String[] args) throws Exception{
File file = new File("scores.txt");
if(file.exists()){
System.out.println("File already exists");
System.exit(0);
}
//Create a file
PrintWriter output = new PrintWriter(file);
//Write formatted out put to the file
output.print("John T smith ");
output.print(90);
output.print(" Eric K Jones ");
output.print(85);
//Close the file
output.close();
}
}
Scanner
import java.util.*;
import java.io.*;
public class ReadData {
public static void main(String[] args) throws Exception{
// Create a File instance
File file = new File("scores.txt");
//Create a Scanner for the file
Scanner input = new Scanner(file);
//Read data from a file
while(input.hasNext()){
String firstname = input.next();
String mi = input.next();
String lastname = input.next();
int score = input.nextInt();
System.out.println(firstname + " " + mi + " " + lastname + " " + score);
}
//Close the file
input.close();
}
}
Example
import java.io.*;
import java.util.*;
public class ReplaceText {
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 4) {
System.out.println(
"Usage: java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(0);
}
// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(0);
}
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(0);
}
// Create input and output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
input.close();
output.close();
}
}