Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Ввод-вывод в потоки в Java"— Presentation transcript:

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

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

3 java.io

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

5 Основные методы потоков
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)

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

7 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 Сохранение объектов в потоки

8 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 Преобразование между символьными и байтовыми потоками

9 Ввод из стандартного потока
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)

10 Чтение целого из входного потока
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);

11 Вывод в поток 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. }

12 Использование файловых потоков
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")

13 Класс 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

14 Копирование файла 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();

15 Копирование файла /** 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); }

16 Копирование файла /** 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(); } Копирование файла

17 /** 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));

18 Переназначение стандартных потоков
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 }

19 Дублирование потока при записи
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(); } }

20 Кодировки файлов 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); }

21 Двоичные данные 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); }

22 Сериализация объектов
/** 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; }

23 /** 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();

24 Чтение и запись архивов
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);; }}}

25 Работа с каналами 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){} } }

26 Как объединять потоки 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); }

27 Операции с файлами 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

28 Операции с файлами 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")); }


Download ppt "Ввод-вывод в потоки в Java"

Similar presentations


Ads by Google