Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JAVA Programming Language Chapter 9. Input/Output with Java.io Juho Kim Department of Computer Science and Engineering Sogang University 9 -1 java.io package Provides for system input and output through data streams, serialization and the file system. Java Virtual Machine connects data stream to input/output hardware. Data stream makes JAVA I/O independent of machines File and Directory FileWriter FileReader class BufferedWriter BufferedReader class FileOutputStream FileInputStream class BufferedOutputStream BufferedInputStream class DataOutputStream DataInputStream class 9-2 File class File and Directory – File class: An abstract representation of file and directory pathnames. User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames • Constructor File(File parent, String child) Creates a new File instance from a parent abstract pathname and a child pathname string. File(String pathname) Creates a new File instance by converting the given pathname string into an abstract pathname File(String pathname, String filename) Creates a new File instance by pathname string and filename string 9 -3 • Methods boolean canRead() if readable return true boolean canWrite() if write allowed return true boolean delete() delete file and return true boolean exists() String getAbsolutePath() return pathname String getParent() return parent directory name String getName() return file name boolean isFile() boolean isDirectory() long lastModified() return milliseconds from 1970/1/1 until last modified time String[] list() return filenames from directory 9 -4 FileDirDemo1.java import java.io.File; class FileDirDemo1 { public static void main(String args[]) { String directory = "c:/jdk1.4"; File f1 = new File(directory); if (f1.isDirectory()) { System.out.println("Directory : " + directory); System.out.println(" "); String s[] = f1.list(); for(int i=0; i<s.length; i++) { File f = new File(directory + "/" + s[i]); if (f.isDirectory()) { System.out.println(s[i] + " : directory"); } else { System.out.println(s[i] + " : file"); }}} else { System.out.println(“this" +directory + " is not a directory"); } }} 9 -5 FileDirDemo2.java import java.io.File; class FileDirDemo2 { static void p(String s) { System.out.println(s); } public static void main(String args[]) { File f1 = new File("c:/jdk1.4/README.txt"); p("f1.getName(): " + f1.getName()); p("f1.getPath(): " + f1.getPath()); p("f1.getAbsolutePath(): " + f1.getAbsolutePath()); p("f1.exists(): " + f1.exists()); p("f1.canWrite(): " + f1.canWrite()); p("f1.canRead(): " + f1.canRead()); p("f1.isDirectory(): " + f1.isDirectory()); p("f1.isFile(): " + f1.isFile()); p("f1.lastModified(): " + f1.lastModified()); p("f1.length(): " + f1.length() + " bytes"); }} 9 -6 FireWriter and FileReader class – Constructor FileWriter(String filepath) throws IOException FileWriter(String filepath, boolean append) throws IOException FileWriter(File fileObject) throws IOException FileReader(String filepath) FileReader(File fileObject) 9 -7 – Methods void close() closing input/output stream void flush() sending data in output buffer to output device void write(int c)output lower 16-bit of c void write(char buffer[]) output from buffer array void write(char buffer[], int index, int size) void write(String s) void write(String s, int index, int size) int read() return character, if end of file return -1 int read(char buffer[]) int read(char buffer[], int offset, int numChars) 9 -8 FileWriterDemo.java import java.io.*; class FileWriterDemo { public static void main(String args[]) throws Exception { String source = "File Writer \nDemonstration"; char intxt[] = new char[source.length()]; source.getChars(0, source.length(), intxt, 0); FileWriter fw = new FileWriter(args[0]); fw.write(intxt); fw.close(); } } 9 -9 FileReaderDemo.java import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader(args[0]); int i; while((i = fr.read()) != -1) { System.out.print((char) i); } fr.close(); } } 9 -10 BufferedWriter and BufferedReader class – BufferedWriter class Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes. – BufferedReader class Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. 9 -11 – Constructor BufferedWriter(Writer outputStream) BufferedWriter(Writer outputStream, int bufSize) BufferedReader(Reader inputStream) BufferedReader(Reader inputStream, int bufSize) Writer class : Abstract class for writing to character streams Reader class : Abstract class for reading to character streams 9 -12 BufferedWriterDemo.java import java.io.*; class BufferedWriterDemo { public static void main(String args[]) throws Exception { String source = "Buffered Writer \nDemonstration"; char intxt[] = new char[source.length()]; source.getChars(0, source.length(), intxt, 0); FileWriter fw = new FileWriter(args[0]); BufferedWriter bw = new BufferedWriter(fw); bw.write(intxt); bw.close(); } } 9 -13 BufferedReaderDemo.java import java.io.*; class BufferedReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.print(s); } br.close(); } } 9 -14 FileOutputStream and FileInputStream – OutputStream class • This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. • Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. – InputStream class • This abstract class is the superclass of all classes representing an input stream of bytes. • Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input. 9 -15 – FileOutputStream java.lang.Object | + --java.io.OutputStream | + --java.io.FileOutputStream public class FileOutputStream extends OutputStream A file output stream is an output stream for writing data to a File or to a FileDescriptor. What files are available or may be created depends on the host environment. 9 -16 – Constructor FileOutputStream(String filepath) throws IOException filepath constains pathname and filename FileOutputStream(String filepath, boolean append) throws IOException if append is true, append at the end of the file otherwise, overwirte FileOutputStream(File fileObject) throws IOException fileObject is a specific file 9 -17 – FileInputStream class java.lang.Object | + --java.io.InputStream | + --java.io.FileInputStream public class FileInputStream extends InputStream A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. – Constructor FileInputStream(String filepath) throws FileNotFoundException FileInputStream(File fileObject) throws FileNotFoundException 9 -18 FileOutputStreamDemo.java import java.io.*; class FileOutputStreamDemo { public static void main(String args[]) throws IOException { FileOutputStream fos = new FileOutputStream(args[0]); for(int i = 0; i < 5; i++) { fos.write(i); } fos.close(); System.out.println("ByteStreamFile is created"); } } 9 -19 FileInputStreamDemo.java import java.io.*; class FileInputStreamDemo { public static void main(String args[]) throws IOException { FileInputStream fis = new FileInputStream(args[0]); int i; while((i = fis.read()) != -1) { System.out.println(i); } fis.close(); System.out.println("ByteStreamFile is read and printed"); } } 9 -20 BufferedOutputStream and BufferedInputStream class – The class BufferedOutputStream implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. The data is written into an internal buffer, and then written to the underlying stream if the buffer reaches its capacity, the buffer output stream is closed, or the buffer output stream is explicitly flushed. – When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. 9 -21 BufferedOutputStreamDemo.java import java.io.*; class BufferedOutputStreamDemo { public static void main(String args[]) throws IOException { FileOutputStream fos = new FileOutputStream(args[0]); BufferedOutputStream bos = new BufferedOutputStream(fos); for(int i = 0; i < 5; i++) { bos.write(i); } bos.close(); System.out.println("ByteStreamFile is created"); } } 9 -22 BufferedInputStreamDemo.java import java.io.*; class BufferedInputStreamDemo { public static void main(String args[]) throws IOException { FileInputStream fis = new FileInputStream(args[0]); BufferedInputStream bis = new BufferedInputStream(fis); int i; while((i = bis.read()) != -1) { System.out.println(i); } bis.close(); System.out.println("ByteStreamFile is read and printed"); } } 9 -23 DataOutputStream and DataInputStream class – A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in. – A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream. – Constructor DataOutputStream(OutputStream outputStream) DataInputStream(InputStream inputStream) 9 -24 9 -25 9 -26 DataOutputStreamDemo.java import java.io.*; class DataOutputStreamDemo { public static void main(String args[])throws IOException { FileOutputStream fos = new FileOutputStream(args[0]); DataOutputStream dos = new DataOutputStream(fos); dos.writeBoolean(false); dos.writeByte(Byte.MAX_VALUE); dos.writeChar('A'); dos.writeDouble(Double.MAX_VALUE); dos.writeFloat(Float.MAX_VALUE); dos.writeInt(Integer.MAX_VALUE); dos.writeLong(Long.MAX_VALUE); dos.writeShort(Short.MAX_VALUE); fos.close(); } } 9 -27 DataInputStreamDemo.java import java.io.*; class DataInputStreamDemo { public static void main(String args[])throws IOException { FileInputStream fis = new FileInputStream(args[0]); DataInputStream dis = new DataInputStream(fis); System.out.println("Boolean : " + dis.readBoolean()); System.out.println("Byte.MAX_VALUE : " + dis.readByte()); System.out.println("Character : " + dis.readChar()); System.out.println("Double.MAX_VALUE : " + dis.readDouble()); System.out.println("Float.MAX_VALUE : " + dis.readFloat()); System.out.println("Integer.MAX_VALUE : " + dis.readInt()); System.out.println("Long.MAX_VALUE : " + dis.readLong()); System.out.println("Short.MAX_VALUE : " + dis.readShort()); fis.close(); } } 9 -28