Programming Fundamentals Lab Manual 11
Programming Fundamentals Lab Manual 11
Statement Purpose:
In this lab you will experiment with the Java Input/Output components by implementing two programs that read input from a file and write output to a file.
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.
Activity Outcomes:
Student will be able to:
- Describe the concept of an I/O stream
- Explain the difference between text files and binary files
- Save data
- Read data
1) Stage J (Journey)
Introduction
The character input and output shown so far has used the pre-defined “standard” streams System.in and System.out. Obviously in many real applications it is necessary to access named files. In many programming languages there is a logical (and practical) distinction made between files that will contain text and those while will be used to hold binary information. Files processed as binary are thought of as sequences of 8- bit bytes, while ones containing text model sequences of characters.
Java uses names typically based on the word Stream for binary access, and Reader and Writer for text. So when you read the documentation expect to find two broadly parallel sets of mechanisms, one for each style of access.
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Creates InputStreamReader to read standard input stream until the user types a “q”.
Solution:
import java.io.*; public class ReadConsole {
public static void main(String args[]) throws IOException
{ InputStreamReader cin = null;
try { cin = new
InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c; do { c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Activity 2:
Write a java program to demonstrate InputStream and OutputStream
Solution:
import java.io.*; public class fileStreamTest { public static void main(String args[]) { try { byte bWrite [] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + " "); } is.close(); }catch(IOException e) { System.out.print("Exception"); } } }
Activity 3:
A java program to show that a method called to read characters, and that it returns the integer -1 at end of file.
Solution:
import java.io.*; public class InputOP1 { public static void main(String args[]) throws IOException { Reader r = new FileReader("filename"); int c; while ((c = r.read()) != -1) { System.out.printf("Char code %x is \"%<c\"%n", c);} r.close(); } }
Activity 3:
Write a java program by using list( ) method provided by File object to list down all the files and directories available in a directory.
Solution:
import java.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } }catch(Exception e) { // if any error occurs e.printStackTrace(); } } }
Activity 4:
Write a java program to compare paths of two files? Solution: import java.io.File; public class Main { public static void main(String[] args) { File file1 = new File("C:/File/demo1.txt"); File file2 = new File("C:/java/demo1.txt"); if(file1.compareTo(file2) == 0) { System.out.println("Both paths are same!"); } else { System.out.println("Paths are not same!"); } } }
Activity 5:
Write a java program to create a new file?
Solution:
import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { try {
File file = new File("C:/myfile.txt");
if(file.createNewFile())System.out.println("Success!"); else System.out.println ("Error, file already exists.");
} catch(IOException ioe) { ioe.printStackTrace();
}
}
}
Activity 6:
Write a java program to create a new file (another way)?
Solution:
import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; public class JavaApplication1 { public static void main(String[] args) throws IOException { createFileUsingFileClass(); createFileUsingFileOutputStreamClass(); createFileIn_NIO(); } private static void createFileUsingFileClass() throws IOException { File file = new File("c://testFile1.txt"); //Create the file if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } //Write Content FileWriter writer = new FileWriter(file); writer.write("Test data"); writer.close(); } private static void createFileUsingFileOutputStreamClass() throws IOException { String data = "Test data"; FileOutputStream out = new FileOutputStream("c://testFile2.txt"); out.write(data.getBytes()); out.close(); } private static void createFileIn_NIO() throws IOException { String data = "Test data"; Files.write(Paths.get("c://testFile3.txt"), data.getBytes()); List<String> lines = Arrays.asList("1st line", "2nd line"); Files.write(Paths.get( "file6.txt"), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } }
Activity 7:
Write a java program to get last modification date of a file?
Solution:
import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) { File file = new File("Main.java"); Long lastModified = file.lastModified(); Date date = new Date(lastModified); System.out.println(date); } }
3) Stage v (verify)
Home Activities:
Activity 1: Write a java program to create a file in a specified directory?
Activity 2: Write a java program to check a file exist or not?
4) Stage a2 (assess)
Assignment:
- Write a java program to make a file read-only?
- Write a java program to rename a file?
In this lab you will experiment with the Java Input/Output components by implementing two programs that read input from a file and write output to a file.
Comments
Post a Comment