Share
Embed
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
62 slides
-
Read and Write to Console • Output stream: – System.out
• Input Stream: – System.in -
Using InputStreamReader • To use InputStreamReader – InputStreamReader a =
new InputStreamReader(System.in); • An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset • InputStreamReader has methods for reading one char at a time • We don’t want to read one char at a time from user! -
Using BufferedReader • To use InputStreamReader – BufferedReader a =
new BufferedReader(new InputStreamReader(System.in)); – String mj = a.readLine(); • Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. -
Scanner • Or just use Scanner from Java 1.5! Scanner
s = new Scanner(System.in); String mj = s.nextLine(); -
Read and Write • To Read – FileInputStream • To
Write – FileOutputStream -
Read and Write FileInputStream in = new FileInputStream("output.txt"); FileOutputStream out
= new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); -
Binary vs text • All data are in the end
binary: – 01010101001011100110 • Binary files: bits represent encoded informations, executable instructions or numeric data. • Text files: the binarys represent characters. -
Text files • In text files bits represent printable characters
• In ASCII encoding, one byte represents one character • Encoding is a rule where you map chars to integers. • ‘a’ =97 > => 1100001 -
Testing in Java class CharTest { public static void main(String
[] args) { char myChar1 = 'a'; int myChar2 = 97; System.out.println(myChar1); // 'a' System.out.println(myChar2); // 97 System.out.println( (int) 'a'); // 97 System.out.println((char) 97); // 'a' } } -
InputStreamReader import java.io.*; import java.nio.charset.*; class Main { public static
void main(String [] args) throws Exception { FileInputStream f = new FileInputStream("Main.java"); // Bridge from byte to char InputStreamReader input = new InputStreamReader(f, StandardCharsets.UTF_8); char oneChar = (char) input.read(); System.out.println(oneChar); input.close(); } } By using InputStreamReader/ Writer you can define the encoding! Use OutputStreamWriter for writing -
OutputStreamWriter import java.io.*; import java.nio.charset.*; class Main { public static
void main(String [] args) throws Exception { FileOutputStream f = new FileOutputStream("text.txt"); // Bridge from byte to char OutputStreamWriter writer = new OutputStreamWriter(f, StandardCharsets.UTF_8); writer.write("hello"); writer.close(); } } -
Character Streams • If default encoding is enough, just use
FileReader and FileWriter • To read characters – FileReader • To write characters – FileWriter -
FileReader import java.io.FileReader; import java.io.IOException; public class CharTest { public
static void main(String[] args) throws IOException { FileReader inputStream = new FileReader("CharTest.java"); char oneChar = (char) inputStream.read(); System.out.println(oneChar); inputStream.close(); } } -
FileReader: Reading Multiple Chars import java.io.FileReader; import java.io.IOException; public class
CharTest { public static void main(String[] args) throws IOException { FileReader inputStream = new FileReader("CharTest.java"); int oneChar; while ((oneChar = inputStream.read()) != -1) { System.out.print((char) oneChar); } inputStream.close(); } } -
FileWriter import java.io.FileWriter; import java.io.IOException; public class CharTest { public
static void main(String[] args) throws IOException { FileWriter outputStream = new FileWriter("output.txt"); outputStream.write("hello!"); outputStream.close(); } } -
Buffering • Using unbuffered IO is less efficient than using
buffered IO. • Read stuff to buffer in memory and when buffer is full, write it. Less disk access or network activity -
BufferedReader import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class CharTest
{ public static void main(String[] args) throws IOException { BufferedReader inputStream = new BufferedReader(new FileReader("output.txt")); System.out.println( inputStream.readLine() ); inputStream.close(); } } -
PrintWriter, BufferedWriter • Convenient way of writing files using PrintWriter:
PrintWriter pw = new PrintWriter( new BufferedWriter( new FileWriter("output.txt"))); pw.println("hello!"); pw.close(); -
import java.io.*; public class CharTest { public static void main(String[]
args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader("output.txt")); System.out.println( inputStream.readLine() ); } catch(IOException e) { e.printStackTrace(); } finally { try { if(inputStream != null) { inputStream.close(); } } catch(IOException e) { e.printStackTrace(); } } } } -
Java 7 to the rescue! import java.io.*; public class AutomaticClosing
{ public static void main(String[] args) { try (BufferedReader inputStream = new BufferedReader(new FileReader("output.txt"))){ System.out.println( inputStream.readLine() ); } catch(IOException e) { e.printStackTrace(); } } } -
How? • Virtual Machine will call automatically the close method
upon exiting the try block (like finally) • The resource object must implement AutoCloseable interface • The interface has only one method: close • If closing causes exception, it’s suppressed (ignore). Possible to get it using getSuppressed() method -
API Updates to File System • java.io and java.nio are
updated • Called NIO.2 revision • New classes (java.nio): – Path – Locate a file in a file system • Paths – Convert a URI to Path object – Files – Operate on files, directories and other types of files – FileVisitor – Traversing files in a tree – WatchService – File change modification API -
File (Java 1.0 – 1.7) • File class has very
useful methods: – exists – canRead – canWrite – length – getPath • Example File f = new File(“file.txt”); If(f.exists()) { .. } -
java.nio.file.Path • Absolute or relative path, refers to files in
file system. • Supporting API to java.io.File • File to Path: – File f = new File(”/foo/bar/file.txt”); – Path p = f.toPath(); • Path to File – File f2 = p.toFile(); • Path is an interface! Instantiating using either File or or Paths class – Path p = Paths.get(“file.txt”); -
Demo: Path - class import java.nio.*; import java.nio.file.*; class PathDemo
{ public static void main(String [] args) { Path path = Paths.get("/Users/pohjus/Desktop/demos/file-system/PathDemo.java"); System.out.format("toString: %s%n", path.toString()); System.out.format("getFileName: %s%n", path.getFileName()); System.out.format("getName(0): %s%n", path.getName(0)); System.out.format("getNameCount: %d%n", path.getNameCount()); System.out.format("getParent: %s%n", path.getParent()); System.out.format("getRoot: %s%n", path.getRoot()); } } -
java.nio.file.Files • Features – Copy – Create directories – Create
files – Create links – Use of the “temp” – folder – Delete – Attributes – Modified/Owner/Permission – Read / Write -
java.nio.file.Files • Static methods for reading, writing and manipulating files
and directories • Files uses Path objects! • Methods like – createFile(Path p, ..); – delete(Path p); – move(…) – write(Path p, byte [] b, ..) – readAllLines(Path p, Charset cs) -
Example import java.nio.file.*; import java.nio.*; import java.util.*; import java.io.*; class
FilesExample { public static void main(String [] args) throws IOException { Path src = Paths.get("./FilesExample.java"); Path dest = Paths.get("./dir/FilesExample.java"); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); } } -
Example import java.nio.file.*; import java.nio.*; import java.util.*; import java.io.*; import
java.nio.charset.*; class FilesClass { public static void main(String [] args) throws IOException { Path mypath = new File("FilesClass.java").toPath(); List<String> lines = Files.readAllLines(mypath, Charset.defaultCharset()); for(String line : lines) { System.out.println(line); } } } -
Java 11: readString import java.nio.file.*; import java.nio.*; import java.util.*; import
java.io.*; import java.nio.charset.*; class FilesClass { public static void main(String [] args) throws IOException { Path mypath = new File("FilesClass.java").toPath(); String lines = Files.readString(mypath, Charset.defaultCharset()); } } -
Object Streams • To read and write objects! • How?
– Object class must implement serializable marker interface – Read and write using ObjectInputStream and ObjectOutputStream • Serialization is used in Java RMI -
Example: Car class Car implements Serializable { private String brand;
public Car(String brand) { setBrand(brand); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } } -
Example: Saving and Reading // Save the object fos =
new FileOutputStream("car.dat"); oos = new ObjectOutputStream(fos); oos.writeObject(datsun); // Read the object fis = new FileInputStream("car.dat"); ois = new ObjectInputStream(fis); Car datsun2 = (Car) ois.readObject(); -
Transient • Every attribute of the object is saved into
disk.. except attribute is marked with transient keyword • Mark attributes to transient when the information is secret or uneccessary. • When object is deserializaled, transient attributes values are null -
NIO: High performance IO • java.io is suitable for basic
needs. When there is a need for higher performance, use Java NIO (New I/O) (java.nio) • Less GC, less threads, more efficient use of operating system • Provides scalable I/O operations on both binary and character files. Also a simple parsing facility based on regular expressions • A little bit harder to use than java.io -
Streams vs Blocks • java.io » Stream: movement of single
bytes one at a time. • java.nio » Block: movement of many bytes (blocks) at a time • Processing data by block can be much faster than one byte at a time -
Channels and Buffers • Channels are what streams were in
java.io • All data transferred in java.nio must go through a Channel • Buffer is a container object, before sending data into a channel, the data must be wrapped inside a Buffer • Buffer is an object, which holds an array of bytes -
Buffer Types • There are many classes for buffers. These
classes inherit java.nio.Buffer: • ByteBuffer - byte array • CharBuffer • ShortBuffer • IntBuffer • LongBuffer • FloatBuffer • DoubleBuffer -
About Channels • You never write a byte directly into
a channel. Bytes must be wrapped inside a buffer • Channels are bi-directional • Channels can be opened for reading, writing, or both -
Example: Reading FileInputStream fin = new FileInputStream( "data.txt" ); //
Get a channel via the FileInputStream FileChannel fc = fin.getChannel(); // Create a buffer ByteBuffer buffer = ByteBuffer.allocate( 1024 ); // Read from channel into a buffer fc.read( buffer ); -
Example: Writing FileOutputStream fout = new FileOutputStream( "data.txt" ); //
Get a channel via the FileOutputStream FileChannel fc = fout.getChannel(); // Create a buffer ByteBuffer buffer = ByteBuffer.allocate( 1024 ); // Data to be saved byte [] message = "this will be saved".toByteArray(); // Write into buffer for ( int i=0; i<message.length; i++ ) { buffer.put( message[i] ); } // Flip the buffer, this will be explained later buffer.flip(); // Writes SOME bytes from the buffer! fc.write( buffer ); -
Buffer Internals • Every buffer has position, limit and capacity
• These three variables track the state of the buffer • position: is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit. • limit: is the index of the first element that should not be read or written. A buffer's limit is never negative and is never greater than its capacity • capacity: is the number of elements buffer contains. The capacity of a buffer is never negative and never changes. -
FileInputStream fin = new FileInputStream( “infile.exe” ); FileOutputStream fout =
new FileOutputStream( “outfile.exe” ); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); while (true) { // Reset the buffer buffer.clear(); int numberOfReadBytes = fcin.read( buffer ); if ( numberOfReadBytes == -1 ) { break; } // prepare the buffer to be written to a buffer buffer.flip(); int numberOfWrittenBytes = 0; do { numberOfWrittenBytes += fcout.write( buffer ); } while(numberOfWrittenBytes < numberOfReadBytes); }