Java -- File Read and Write instances

Source: Internet
Author: User
Tags string splitter

Instance Source think in java read: different types of information are returned for reading files as needed. Instance 1 is read using BufferReader. [Java] package io; // use Reader to read import java. io. *; public class BufferedInputFile {// Throw exceptions to console: public static String read (String filename) throws IOException {// use BufferedReader for buffering, bufferedReader in = new BufferedReader (new FileReader (filename); String s; StringBuilder sb = new StringBuilder (); while (s = in. readLine ())! = Null) sb. append (s + "\ n"); in. close (); return sb. toString ();} public static void main (String [] args) throws IOException {System. out. print (read ("C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ BufferedInputFile. java ");} instance 2 read using the StringReader class, in. read () returns the next byte in the form of an int. [Java] package io; // read import java from memory. io. *; public class MemoryInput {public static void main (String [] args) throws IOException {StringReader in = new StringReader (BufferedInputFile. read ("C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ MemoryInput. java "); int c; while (c = in. read ())! =-1) System. out. print (char) c) ;}} instance 3 reads data using the DataInputStream class, And the byte type returned by in. readByte. [Java] package io; // relative to TestEOF. java this method cannot detect whether the byte ends // The Byte-oriented IO class import java. io. *; public class FormattedMemoryInput {public static void main (String [] args) throws IOException {try {DataInputStream in = new DataInputStream (new ByteArrayInputStream (BufferedInputFile. read ("C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ FormattedMemoryInput. java "). getBytes (); while (true) System. out. print (c Har) in. readByte ();} catch (EOFException e) {System. err. println ("End of stream") ;}} another usage, the difference is in 9th rows, using in. available ()! = 0 to determine whether the detection byte ends. The FormattedMemoryInput example does not check whether there are any bytes in the stream at runtime. Therefore, an exception will be thrown at the End of the console: The End of stream usage can avoid this problem. [Java] package io; import java. io. *; public class TestEOF {public static void main (String [] args) throws IOException {DataInputStream in = new DataInputStream (new BufferedInputStream (new FileInputStream ("C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ TestEOF. java "); while (in. available ()! = 0) System. out. print (char) in. readByte () ;}}write: instance 1 Basic files are written into [java] package io; // basic file output import java. io. *; public class BasicFileOutput {static String file = "C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ BasicFileOutput. out "; public static void main (String [] args) throws IOException {BufferedReader in = new BufferedReader (new StringReader (BufferedInputFile. read ("C: \ Users \ zm \ worksp Ace \ Thinking in java \ src \ io \ BasicFileOutput. java "); PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter (file); int lineCount = 1; String s; while (s = in. readLine ())! = Null) out. println (lineCount ++ ":" + s); out. close (); // Show the stored file: System. out. println (BufferedInputFile. read (file);} quick usage. PrintWriter provides a cache operation constructor, saving us from packaging. [Java] package io; // quick usage of the output method. PrintWriter provides the cache operation constructor import java. io. *; public class FileOutputShortcut {static String file = "C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ FileOutputShortcut. out "; public static void main (String [] args) throws IOException {BufferedReader in = new BufferedReader (new StringReader (BufferedInputFile. read ("C: \ Users \ zm \ workspace \ Thinking in java \ src \ io \ FileOutputShortcut. java "); // Here's the shortcut: PrintWriter out = new PrintWriter (file); int lineCount = 1; String s; while (s = in. readLine ())! = Null) out. println (lineCount ++ ":" + s); out. close (); // Show the stored file: System. out. println (BufferedInputFile. read (file);} read and Write tool class [java] //: net/mindview/util/TextFile. java // Static functions for reading and writing text files as // a single string, and treating a file as an ArrayList. package net. mindview. util; import java. io. *; import java. util. *; public class TextFile extends Arr AyList <String> {private static String gpfile = "C: \ Users \ zm \ workspace \ Thinking in java \ src \ net \ mindview \ util \ "; // Read a file as a single string: public static String read (String fileName) {StringBuilder sb = new StringBuilder (); try {BufferedReader in = new BufferedReader (new FileReader (new File (fileName ). getAbsoluteFile (); try {String s; while (s = in. readLine ())! = Null) {sb. append (s); sb. append ("\ n") ;}} finally {in. close () ;}} catch (IOException e) {throw new RuntimeException (e);} return sb. toString ();} // Write a single file in one method call: public static void write (String fileName, String text) {try {PrintWriter out = new PrintWriter (new File (fileName ). getAbsoluteFile (); try {out. print (text);} finally {out. close () ;}} catch (IOException e) {throw new RuntimeException (e) ;}// Read a file, split by any regular expression: public TextFile (String fileName, string splitter) {super (Arrays. asList (read (fileName ). split (splitter); // Regular expression split () often leaves an empty // String at the first position: if (get (0 ). equals ("") remove (0);} // Normally read by lines: public TextFile (String fileName) {this (fileName, "\ n ");} public void write (String fileName) {try {PrintWriter out = new PrintWriter (new File (fileName ). getAbsoluteFile (); try {for (String item: this) out. println (item);} finally {out. close () ;}} catch (IOException e) {throw new RuntimeException (e) ;}// Simple test: public static void main (String [] args) {String file = read (gpfile + "TextFile. java "); write (" d: \ test.txt ", file); TextFile text = new TextFile (" d: \ test.txt "); text. write ("d :\\ test2.txt"); // Break into unique sorted list of words: treeSet <String> words = new TreeSet <String> (new TextFile (gpfile + "TextFile. java "," \ W + "); // Display the capitalized words: System. out. println (words. headSet (""));}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.