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 Макаревич Л. Г. Что такое поток Ввод Открыть поток Читать информацию до конца потока Закрыть поток Вывод Открыть поток Писать информацию, пока она есть Закрыть поток java.io Символьные потоки Основные методы потоков Reader: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) InputStream: int read() 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(int c) int write(byte cbuf[]) int write(byte cbuf[], int offset, int length) Байтовые потоки Тип потока Классы Описание Memory CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream Работа с памятью StringReader StringWriter StringBufferInputStream Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream Каналы, связь потоков между собой File FileReader FileWriter FileInputStream FileOutputStream Работа с файлами Concatenation N/A SequenceInputStream Объединение входных потоков Object Serialization N/A ObjectInputStream ObjectOutputStream Сохранение объектов в потоки 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.*; import java.io.*; public class CatStdin { public class CatStdin { public static void main(String[] av) { public static void main(String[] av) { CatFile c = new CatFile(); try { try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); int b=0; String inputLine; while (true) { while ((inputLine = is.readLine()) != null) { b=System.in.read(); System.out.println(inputLine); System.out.print(b); } } (char) is.close(); } catch (IOException e) { } catch (IOException e) { System.out.println("IOException: " + e); } } } } System.out.println("IOException: " + e); } } Чтение целого из входного потока 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."); pw.println(i + "=" + " the answer."); // using quotes pw.println(i + ('=' + " the answer.")); // parenthesis pw.close(); } } // OK // 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") separatorChar public static final char separatorChar Класс File 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 ';'. See Also: System.getProperty(java.lang.String) 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. Копирование файла 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(); } Копирование файла 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]; /** Read the content of a Stream into a String int */ n; public static String inputStreamToString(InputStream is) throws IOException { // Read a block. If it gets any chars, append them. while ((n = is.read(b)) > 0) { return readerToString(new InputStreamReader(is)); sb.append(b, 0, n); } } /** Write a String as the entire content of a File */ // Only construct the String object once, here. public static void stringToFile(String text, String fileName) throws IOException { return sb.toString(); 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) throws IOException { 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.*; /** Return true if either stream has an error. */ public class TeePrintStream extends PrintStream { public boolean checkError() { protected PrintStream parent; return parent.checkError() || super.checkError(); protected String fileName; } public static void main(String[] args) throws IOException { /** override write(). This is the actual "tee" operation. */ TeePrintStream ts = new TeePrintStream(System.err, "err.log"); public void write(int x) { System.setErr(ts); parent.write(x); System.err.println("An imitation error message"); super.write(x); ts.close(); } // "write once; // write somewhere else." } public TeePrintStream(PrintStream orig, OutputStream os, boolean flush) /** override write(). This is the actual "tee" operation. */ throws IOException { public void write(byte[] x, int o, int l) { super(os, true); parent.write(x, o, l); // "write once; fileName = "(opened Stream)"; super.write(x, o, l); // write somewhere else." parent = orig; } } public TeePrintStream(PrintStream orig, OutputStream os) /** Close both streams. */ throws IOException { public void close() { this(orig, os, true); parent.close(); } super.close(); public TeePrintStream(PrintStream os, String fn) throws IOException { } this(os, fn, true); } /** Flush both streams. */ public TeePrintStream(PrintStream orig, String fn, boolean flush) public void flush() { throws IOException { parent.flush(); this(new FileOutputStream(fn), 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); return; } } } Двоичные данные 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"); InputStreamReader oos1 = new InputStreamReader(gzip1); ch = 0; while(ch!= -1) { ch = oos1.read(); System.out.write(ch);; }}} ZipInputStream gzip1 = new ZipInputStream(f); Работа с каналами class RT extends Thread { import java.io.*; PipedReader pin; class ST extends Thread RT(PipedReader p){pin = p;} { char ch; PipedWriter pout; public void run() FileReader fs; { ST(PipedWriter p){pout = p;} System.out.println("RT started"); public void run() { while ((int)(ch)!= -1 ) try{ { try{ ch =(char) pin.read();}catch(Exception e){} fs = new FileReader("Pipe.java"); System.out.println("RT got" + ch); } System.out.println("ST started"); System.out.println("RT ended "); char c; } do { } c = (char)fs.read(); sleep(1000); class Pipe pout.write(c); { }while ( (int) c!= -1 ); static public void main(String[] a ) throws Exception fs.close(); { System.out.println("ST ended"); PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); }catch(Exception e){} } ST t1 = new ST(pipeOut); } RT t2 = new RT(pipeIn); t1.start(); t2.start(); } } Как объединять потоки 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.*; if (f.canRead()) { public class FileStatus { System.out.println("File is readable."); public static void main(String[] argv) throws IOException { } if (argv.length == 0) { if (f.canWrite()) { System.err.println("Usage: Status filename"); System.exit(1); } } // Report on the modification time. for (int i = 0; i< argv.length; i++) { } System.out.println("File is writable."); Date d = new Date(); status(argv[i]); d.setTime(f.lastModified()); } System.out.println("Last modified " + d); public static void status(String fileName) throws IOException { System.out.println("---" + fileName + "---"); // See if file, directory, or other. If file, print size. if (f.isFile()) { File f = new File(fileName); // Report on the file's size if (!f.exists()) { System.out.println("File size is " + f.length() + " bytes System.out.println("file not found"); } else if (f.isDirectory()) { System.out.println(); System.out.println("It's a directory"); // Blank line return; } else { } System.out.println("I dunno! Neither a file nor a direc System.out.println("Canonical name " + f.getCanonicalPath()); } String p = f.getParent(); System.out.println(); if (p != null) { } System.out.println("Parent directory: " + p); } } // blank line between en Операции с файлами 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")); } }