Ввод-вывод в потоки в Java

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
Streams and Files The objectives of this chapter are: To understand the principles of I/O streams and where to use them To understand the options and limitations.
Java I/O and Java Networking (Client Side) Yoshi.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Streams and Files CMPS Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
The Java I/O Classes and Interfaces cont’d
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming Language (3) - Input/Output Stream –
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
Chapter 10: I/O Streams Input Streams Output Streams
The Java IO System Different kinds of IO Different kinds of operations
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Files and Streams The material in this chapter is not tested on the AP CS exams.
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Ch14 Files and Streams OBJECTIVES
Lesson 8: More File I/O February 5, 2008
Object Writing in files
12: The Java I/O System stream model.
I/O Basics.
Java Methods ("Chapter %d", 14); Streams and Files A & AB
File.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
File I/O & collection frame work
Programming in Java Files and I/O Streams
Java’s Hierarchy Input/Output Classes and Their Purpose
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Stream Oriented I/O Computer Programming II Dr. Tim Margush
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
Java IO Packages Prepared by Mrs.S.Amudha AP/SWE
David Davenport Spring 2005
Presentation transcript:

Ввод-вывод в потоки в Java Макаревич Л. Г.

Что такое поток Открыть поток Читать информацию до конца потока Ввод Закрыть поток Ввод Вывод Открыть поток Писать информацию, пока она есть Закрыть поток

java.io

Символьные потоки

Основные методы потоков Reader: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) InputStream: int read(byte cbuf[]) int read(byte cbuf[], int offset, int length) Writer: int write(int c) int write(char cbuf[]) int write(char cbuf[], int offset, int length) OutputStream: int write(byte cbuf[]) int write(byte cbuf[], int offset, int length)

Байтовые потоки

PipedReader PipedWriter PipedInputStream PipedOutputStream I/O Streams Тип потока Классы Описание Memory CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream Работа с памятью StringReader StringWriter StringBufferInputStream Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream Каналы, связь потоков между собой File FileReader FileWriter FileInputStream FileOutputStream Работа с файлами Concatenation N/A SequenceInputStream Объединение входных потоков Object Serialization ObjectInputStream ObjectOutputStream Сохранение объектов в потоки

DataInputStream DataOutputStream Работа с примитивными типами данных Data Conversion N/A  DataInputStream DataOutputStream Работа с примитивными типами данных Counting LineNumberReader LineNumberInputStream Подсчет строк при вводе Peeking Ahead PushbackReader PushbackInputStream Возврат в поток при чтении Printing PrintWriter PrintStream Печать в текстовом формате Buffering BufferedReader BufferedWriter BufferedInputStream BufferedOutputStream Буферизация Filtering FilterReader FilterWriter FilterInputStream FilterOutputStream Абстрактные классы для создания фильтрующих потоков Converting between Bytes and Characters InputStreamReader OutputStreamWriter Преобразование между символьными и байтовыми потоками

Ввод из стандартного потока import java.io.*; public class CatStdin { public static void main(String[] av) { try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); String inputLine; while ((inputLine = is.readLine()) != null) { System.out.println(inputLine); } is.close(); } catch (IOException e) { System.out.println("IOException: " + e); import java.io.*; public class CatStdin { public static void main(String[] av) { CatFile c = new CatFile(); try { int b=0; while (true) { b=System.in.read(); System.out.print(b); } } catch (IOException e) { System.out.println("IOException: " + e); (char)

Чтение целого из входного потока import java.io.*; public class ReadStdinInt { public static void main(String[] ap) { String line = null; int val = 0; try { BufferedReader is = new BufferedReader( new InputStreamReader(System.in)); line = is.readLine(); val = Integer.parseInt(line); } catch (NumberFormatException ex) { System.err.println("Not a valid number: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } System.out.println("I read this number: " + val);

Вывод в поток import java.io.*; public class PrintStandardOutput { public static void main(String[] args) { String myAnswer = "No, and that's final,"; System.out.println("Hello World of Java"); System.out.println("The answer is " + myAnswer + " at this time."); PrintWriter pw = new PrintWriter(System.out); pw.println("The answer is " + myAnswer + " at this time."); int i = 42; pw.println(i + '=' + " the answer."); // WRONG pw.println("Note: " + i + '=' + " the answer."); // OK pw.println(i + "=" + " the answer."); // using quotes pw.println(i + ('=' + " the answer.")); // parenthesis pw.close(); // If you open it, you close it. }

Использование файловых потоков import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } System.getProperty("file.encoding")

Класс File separatorChar public static final char separatorChar The system-dependent default name-separator character. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\'. See Also: System.getProperty(java.lang.String) separator public static final String separator The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar. pathSeparatorChar public static final char pathSeparatorChar The system-dependent path-separator character. This field is initialized to contain the first character of the value of the system property path.separator. This character is used to separate filenames in a sequence of files given as a path list. On UNIX systems, this character is ':'; on Microsoft Windows systems it is ';'. pathSeparator public static final String pathSeparator The system-dependent path-separator character, represented as a string for convenience. This string contains a single character, namely pathSeparatorChar. Класс File

Копирование файла public static void copyFile(String inName, String outName) throws FileNotFoundException, IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(inName)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outName)); copyFile(is, os, true); } public static void copyFile(InputStream is, OutputStream os, boolean close) throws IOException { int b; // the byte read from the file while ((b = is.read()) != -1) { os.write(b); } is.close(); if (close) os.close();

Копирование файла /** Copy a file from a filename to a PrintWriter. */ public static void copyFile(Reader is, Writer os, boolean close) throws IOException { int b; // the byte read from the file while ((b = is.read()) != -1) { os.write(b); } is.close(); if (close) os.close(); /** Copy a file from a filename to a PrintWriter. */ public static void copyFile(String inName, PrintWriter pw, boolean close) throws FileNotFoundException, IOException { BufferedReader is = new BufferedReader(new FileReader(inName)); copyFile(is, pw, close); }

Копирование файла /** Open a file and read the first line from it. */ public static String readLine(String inName) throws FileNotFoundException, IOException { BufferedReader is = new BufferedReader(new FileReader(inName)); String line = null; line = is.readLine(); is.close(); return line; } /** The size of blocking to use */ protected static final int BLKSIZ = 8192; /** Copy a data file from one filename to another, alternate method. * As the name suggests, use my own buffer instead of letting * the BufferedReader allocate and use the buffer. */ public void copyFileBuffered(String inName, String outName) throws FileNotFoundException, IOException { InputStream is = new FileInputStream(inName); OutputStream os = new FileOutputStream(outName); int count = 0; // the byte count byte b[] = new byte[BLKSIZ]; // the bytes read from the file while ((count = is.read(b)) != -1) { os.write(b, 0, count); is.close(); os.close(); } Копирование файла

/** Read the entire content of a Reader into a String */ public static String readerToString(Reader is) throws IOException { StringBuffer sb = new StringBuffer(); char[] b = new char[BLKSIZ]; int n; // Read a block. If it gets any chars, append them. while ((n = is.read(b)) > 0) { sb.append(b, 0, n); } // Only construct the String object once, here. return sb.toString(); /** Read the content of a Stream into a String */ public static String inputStreamToString(InputStream is) throws IOException { return readerToString(new InputStreamReader(is)); } /** Write a String as the entire content of a File */ public static void stringToFile(String text, String fileName) BufferedWriter os = new BufferedWriter(new FileWriter(fileName)); os.write(text); os.flush(); os.close(); /** Open a BufferedReader from a named file. */ public static BufferedReader openFile(String fileName) return new BufferedReader(new FileReader(fileName));

Переназначение стандартных потоков import java.io.*; public class Redirect { public static void main(String[] argv) throws IOException { String LOGFILENAME = "error.log"; System.setErr(new PrintStream(new FileOutputStream(LOGFILENAME))); System.out.println("Please look for errors in " + LOGFILENAME); // Now to see somebody else's code writing to stderr... int a[] = new int[5]; a[10] = 0; // here comes an ArrayIndexOutOfBoundsException }

Дублирование потока при записи import java.io.*; public class TeePrintStream extends PrintStream { protected PrintStream parent; protected String fileName; public static void main(String[] args) throws IOException { TeePrintStream ts = new TeePrintStream(System.err, "err.log"); System.setErr(ts); System.err.println("An imitation error message"); ts.close(); } public TeePrintStream(PrintStream orig, OutputStream os, boolean flush) throws IOException { super(os, true); fileName = "(opened Stream)"; parent = orig; public TeePrintStream(PrintStream orig, OutputStream os) this(orig, os, true); public TeePrintStream(PrintStream os, String fn) throws IOException { this(os, fn, true); public TeePrintStream(PrintStream orig, String fn, boolean flush) this(new FileOutputStream(fn), flush); /** Return true if either stream has an error. */ public boolean checkError() { return parent.checkError() || super.checkError(); } /** override write(). This is the actual "tee" operation. */ public void write(int x) { parent.write(x); // "write once; super.write(x); // write somewhere else." public void write(byte[] x, int o, int l) { parent.write(x, o, l); // "write once; super.write(x, o, l); // write somewhere else." /** Close both streams. */ public void close() { parent.close(); super.close(); /** Flush both streams. */ public void flush() { parent.flush(); super.flush(); } }

Кодировки файлов import java.io.*; public class UseConverters { public static void main(String[] args) { try { BufferedReader from = new BufferedReader( new InputStreamReader( new FileInputStream("kanji.txt"), "Cp1251")); PrintWriter to = new PrintWriter( new OutputStreamWriter( new FileOutputStream("sverige.txt"), "UNICODE")); // reading and writing here... String line = from.readLine(); System.out.println("-->" + line + "<--"); to.println(line); from.close(); to.close(); } catch (UnsupportedEncodingException exc) { System.err.println("Bad encoding" + exc); return; } catch (IOException err) { System.err.println("I/O Error: " + err); }

Двоичные данные import java.io.*; public class WriteBinary { public static void main(String[] argv) throws IOException { int i = 42; double d = Math.PI; String FILENAME = "binary.dat"; DataOutputStream os = new DataOutputStream( new FileOutputStream(FILENAME)); os.writeInt(i); os.writeDouble(d); os.close(); System.out.println("Wrote " + i + ", " + d + " to file " + FILENAME); }

Сериализация объектов /** Simple data class to be serialized. */ class MyData implements Serializable { String userName; String passwordCypher; transient String passwordClear; public MyData(String name, String clear) { userName = name; // Save the clear text p/w in the object, it won't get serialized passwordClear = clear; // So we must save the encryption! Encryption not shown here. passwordCypher = DES.encrypt(passwordClear); } class DES { // Obviously just a placeholder. public static String encrypt(String s) { return s; }

/** Demonstrate use of Serialization. */ public class SerialDemo { protected static final String FILENAME = "serial.dat"; public static void main(String[] s) throws IOException { new SerialDemo().save(); new SerialDemo().dump(); } /** The save method in an appliction */ public void save() throws IOException { ArrayList v = new ArrayList(); // Gather the data MyData u1 = new MyData("Ian Darwin", "secret_java_cook"); v.add(new Date()); v.add(u1); v.add(new MyData("Abby Brant", "dujordian")); write(v); /** Does the actual serialization */ public void write(Object theGraph) throws IOException { // Save the data to disk. ObjectOutputStream os = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(FILENAME))); os.writeObject(theGraph); os.close(); public void dump() throws IOException { ObjectInputStream is = new ObjectInputStream( new FileInputStream(FILENAME)); System.out.println(is.readObject()); is.close();

Чтение и запись архивов import java.io.*; import java.util.zip.*; class Serial { public static void main(String[] a) throws Exception { FileInputStream fis = new FileInputStream("Serial.java"); InputStreamReader ios = new InputStreamReader(fis); FileOutputStream fos = new FileOutputStream("serial"); ZipOutputStream gzip = new ZipOutputStream(fos); OutputStreamWriter oos = new OutputStreamWriter(gzip); try{ int ch = 0; while(ch!= -1) { ch = ios.read(); oos.write((char)ch); }oos.flush(); }catch(Exception e){} ios.close(); oos.flush(); oos.close(); FileInputStream f = new FileInputStream("serial"); ZipInputStream gzip1 = new ZipInputStream(f); InputStreamReader oos1 = new InputStreamReader(gzip1); ch = 0; while(ch!= -1) { ch = oos1.read(); System.out.write(ch);; }}}

Работа с каналами class RT extends Thread { PipedReader pin; RT(PipedReader p){pin = p;} char ch; public void run() System.out.println("RT started"); while ((int)(ch)!= -1 ) { try{ ch =(char) pin.read();}catch(Exception e){} System.out.println("RT got" + ch); } System.out.println("RT ended "); } class Pipe static public void main(String[] a ) throws Exception PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); ST t1 = new ST(pipeOut); RT t2 = new RT(pipeIn); t1.start(); t2.start(); import java.io.*; class ST extends Thread { PipedWriter pout; FileReader fs; ST(PipedWriter p){pout = p;} public void run() { try{ fs = new FileReader("Pipe.java"); System.out.println("ST started"); char c; do { c = (char)fs.read(); sleep(1000); pout.write(c); }while ( (int) c!= -1 ); fs.close(); System.out.println("ST ended"); }catch(Exception e){} } }

Как объединять потоки import java.io.*; import java.util.*; class Seq { public static void main(String [] a) throws IOException FileInputStream if1 = new FileInputStream("Seq.java"); FileInputStream if2 = new FileInputStream("aaa.java"); InputStream if3 = new SequenceInputStream(if1,if2); int q; while ((q = if3.read())!= -1) System.out.print((char)q); }

Операции с файлами import java.io.*; import java.util.*; public class FileStatus { public static void main(String[] argv) throws IOException { if (argv.length == 0) { System.err.println("Usage: Status filename"); System.exit(1); } for (int i = 0; i< argv.length; i++) { status(argv[i]); } } public static void status(String fileName) throws IOException { System.out.println("---" + fileName + "---"); File f = new File(fileName); if (!f.exists()) { System.out.println("file not found"); System.out.println(); // Blank line return; System.out.println("Canonical name " + f.getCanonicalPath()); String p = f.getParent(); if (p != null) { System.out.println("Parent directory: " + p); if (f.canRead()) { System.out.println("File is readable."); } if (f.canWrite()) { System.out.println("File is writable."); // Report on the modification time. Date d = new Date(); d.setTime(f.lastModified()); System.out.println("Last modified " + d); // See if file, directory, or other. If file, print size. if (f.isFile()) { // Report on the file's size System.out.println("File size is " + f.length() + " bytes."); } else if (f.isDirectory()) { System.out.println("It's a directory"); } else { System.out.println("I dunno! Neither a file nor a directory!"); System.out.println(); // blank line between entries

Операции с файлами import java.io.*; public class Rename { public static void main(String[] argv) throws IOException { File f = new File("Rename.java~"); // backup of this source file. f.renameTo(new File("junk.dat")); }