Java I/O classic code example

Source: Internet
Author: User
Package IO; import java. Io. *; public class filedirectorydemo {public static void main (string [] ARGs) {// if no parameter is specified, the default value is the current directory. If (ARGs. Length = 0) {ARGs = new string [] {"." };}try {// create a file object in the specified directory. File currentpath = new file (ARGs [0]); // create a file object in the temp directory in the specified directory. File temppath = new file (currentpath, "Temp"); // use the "temppath" object to create the temp directory under the specified directory. Temppath. mkdir (); // create two files in the temp directory. File temp1 = new file (temppath, "temp1.txt"); temp1.createnewfile (); file temp2 = new file (temppath, "temp2.txt"); temp2.createnewfile (); // recursively display the content of the specified directory. System. Out. println ("display the content of the specified directory"); listsubdir (currentpath); // modify the file name to "temp1.txtworkflow ". File temp1new = new file (temppath, "temp.txt"); temp1.renameto (temp1new); // recursively display the contents of the temp subdirectory. System. Out. println ("show temp sub-directory content after file name change"); listsubdir (temppath); // Delete the “temp2.txt file ". Temp2.delete (); // recursively display the contents of the temp sub-directory. System. out. println ("the contents of the temp subdirectory are displayed after the file is deleted"); listsubdir (temppath);} catch (ioexception e) {system. err. println ("ioexception") ;}// recursively display the content of the specified directory. Static void listsubdir (File currentpath) {// gets the list of contents in the specified directory. String [] filenames = currentpath. list (); try {for (INT I = 0; I <filenames. length; I ++) {file F = new file (currentpath. getpath (), filenames [I]); // if it is a directory, the directory NAME IS DISPLAYED, recursively called, and the sub-directory content is displayed. If (F. isdirectory () {// display the directory in a standard path format. System. Out. println (F. GetCanonicalPath (); // recursively calls and displays subdirectories. Listsubdir (f);} // if it is a file, the file name is displayed, excluding the path information. Else {system. out. println (F. getname () ;}} catch (ioexception e) {system. err. println ("ioexception") ;}} package IO; import Java. io. *; public class fileexample {public fileexample () {super (); // call the constructor of the parent class} public static void main (string [] ARGs) {try {string OUTFILE = "demoout. XML "; // defines a variable used to identify the output file string infile =" demoin. XML "; // defines a variable used to identify the input file dataoutputstream dt = new dataoutpu Tstream (New bufferedoutputstream (New fileoutputstream (OUTFILE);/*** use fileoutputstream to define an input stream file, * Then use buferedoutputstream to call the fileoutputstream object to generate a buffer output stream * Then use dataoutputstream to call the buferedoutputstream object to generate a data formatting output stream */bufferedwriter newfile = new bufferedwriter, "GBK"); // processing of Chinese data datainputstream raffile1 = new datainputstream (New bufferedinputstream (New fileinputstream (infil E);/*** use fileinputstream to define an input stream file. * Then use buferedinputstream to call the fileinputstream object to generate a buffer output stream *, then, use datainputstream to call the buferedinputstream object to generate a data formatted output stream */bufferedreader raffile = new bufferedreader (New inputstreamreader (raffile1, "GBK ")); // processing of Chinese Characters String xmlcontent = ""; char tag = 0; // The file ends with zero characters while (tag! = (Char) (-1) {xmlcontent = xmlcontent + tag + raffile. readline () + '';} newfile. write (xmlcontent); newfile. flush (); // clear the newfile buffer. close (); raffile. close (); system. GC (); // force immediate garbage collection to release the memory.} Catch (nullpointerexception exc) {exc. printstacktrace ();} catch (Java. lang. indexoutofboundsexception outb) {system. out. println (outb. getmessage (); outb. printstacktrace ();} catch (filenotfoundexception Fex) {system. out. println ("Fex" + Fex. getmessage ();} catch (ioexception iex) {system. out. println ("iex" + iex. getmessage () ;}} package IO; import Java. io. *; public class filerandomrw {// The number of persons to be entered. Public static int number = 3; public static void main (string [] ARGs) {persons [] People = new persons [number]; people [0] = new persons ("Zhang Feng", 26,200 0, "N"); People [1] = new persons ("yanna", 25,500 00, "Y"); People [2] = new persons ("Li Peng", 50,700 0, "F"); try {dataoutputstream out = new dataoutputstream (New fileoutputstream ("peoplerandom. dat "); // Save the personnel data to" peoplerandom. dat. Writedata (people, out); // close the stream. Out. Close (); // read data in reverse order from the binary file "peoplerandom. dat. Randomaccessfile inout = new randomaccessfile ("peoplerandom. dat", "RW"); persons [] inpeople = readdatareverse (inout); // output the read data. System. out. println ("Raw data:"); For (INT I = 0; I <inpeople. length; I ++) {system. out. println (inpeople [I]);} // modify the third record of the file. Inpeople [2]. setsalary (4500); // write the Modification result to a file. Inpeople [2]. writedata (inout, 3); // close the stream. Inout. Close (); // The third record read from the file and output it to verify the Modification result. Randomaccessfile in = new randomaccessfile ("peoplerandom. dat", "R"); Persons in3people = new persons (); // read the third record randomly. In3people. readdata (in, 3); // close the stream. In. close (); system. out. println ("modified records"); system. out. println (in3people);} catch (ioexception exception) {system. err. println ("ioexception") ;}// write data to the output stream. Static void writedata (persons [] P, dataoutputstream out) throws ioexception {for (INT I = 0; I <p. length; I ++) {P [I]. writedata (out) ;}// reads data from the input stream in reverse order. Static persons [] readdatareverse (randomaccessfile in) throws ioexception {// obtain the number of records. Int record_num = (INT) (IN. Length ()/persons. record_length); persons [] P = new persons [record_num]; // reads data in reverse order. For (INT I = record_num-1; I> = 0; I --) {P [I] = new persons (); // locate the file. In. seek (I * persons. record_length); P [I]. readdata (in, I + 1);} return P ;}} class persons {private string name; private int age; // 4 bytes private double salary; // eight bytes private string married; public static final int name_length = 20; // Name Length public static final int married_length = 2; // marital status length public static final int record_length = name_length * 2 + 4 + 8 + married_length * 2; public persons () {} Public persons (string N, int A, double S) {name = N; age = A; salary = s; married = "F";} public persons (string N, int A, double S, string m) {name = N; age = A; salary = s; married = m;} Public String getname () {return name ;} public int getage () {return age;} public double getsalary () {return salary;} Public String getmarried () {return married;} Public String setname (string N) {n Ame = N; return name;} public int setage (int A) {age = A; return age;} public double setsalary (double S) {salary = s; return salary ;} public String setmarried (string m) {married = m; return married;} // set the output format. Public String tostring () {return getclass (). getname () + "[name =" + name + ", age =" + age + ", salary =" + salary + ", married = "+ Married +"] ";} // write a fixed-length record, that is, a person's data to the output stream. Public void writedata (dataoutput out) throws ioexception {fixstringio. writefixstring (name, name_length, out); out. writeint (AGE); out. writedouble (salary); fixstringio. writefixstring (married, married_length, out);} // write a fixed-length record to the random read file. Private void writedata (randomaccessfile out) throws ioexception {fixstringio. writefixstring (name, name_length, out); out. writeint (AGE); out. writedouble (salary); fixstringio. writefixstring (married, married_length, out);} // randomly write a fixed-length record to the specified position of the output stream. Public void writedata (randomaccessfile out, int N) throws ioexception {out. seek (n-1) * record_length); writedata (out);} // randomly reads a record from the input stream, that is, a person's data. Private void readdata (randomaccessfile in) throws ioexception {name = fixstringio. readfixstring (name_length, In); age = in. readint (); salary = in. readdouble (); married = fixstringio. readfixstring (married_length, In);} // randomly reads records at the specified position from the input stream. Public void readdata (randomaccessfile in, int N) throws ioexception {In. seek (n-1) * record_length); readdata (in );}} // read and write fixed-length Unicode strings from the file class fixstringio {// read the fixed-length Unicode string. Public static string readfixstring (INT size, datainput in) throws ioexception {stringbuffer B = new stringbuffer (size); int I = 0; Boolean more = true; while (more & I <size) {char CH = in. readchar (); I ++; If (CH = 0) {more = false;} else {B. append (CH) ;}// skip the remaining bytes. In. skipbytes (2 * (size-I); return B. tostring () ;}// write a fixed-length Unicode string. Public static void writefixstring (string S, int size, dataoutput out) throws ioexception {int I; for (I = 0; I <size; I ++) {char CH = 0; if (I <S. length () {CH = S. charat (I);} Out. writechar (CH) ;}} package IO; import Java. io. *; import Java. util. *; public class filerw {// number of persons to be entered. Public static int number = 3; public static void main (string [] ARGs) {person [] People = new person [number]; // temporary string array that temporarily holds the input data. String [] field = new string [4]; // initialize the field array. For (INT I = 0; I <4; I ++) {field [I] = "" ;}// Io operations must capture Io exceptions. Try {// adds control to the field array. Int fieldcount = 0; // use system. In to construct inputstreamreader and then bufferedreader. Bufferedreader stdin = new bufferedreader (New inputstreamreader (system. in); For (INT I = 0; I <number; I ++) {fieldcount = 0; system. out. println ("the number" + (I + 1) + "person"); system. out. println ("Enter name, age, salary, married (optional), please separate fields by ':'"); // read a row. String personstr = stdin. Readline (); // you can specify the delimiter. Stringtokenizer ST = new stringtokenizer (personstr, ":"); // you can determine whether a separator is available. While (St. hasmoretokens () {field [fieldcount] = ST. nexttoken (); fieldcount ++;} // if married is input, field [3] is not blank and the person constructor with four parameters is called. If (field [3]! = "") {People [I] = new person (field [0], integer. parseint (field [1]), double. parsedouble (field [2]), field [3]); // leave field [3] Blank for future input. Field [3] = "";} // if married is not input, field [3] Is null and the person constructor with three parameters is called. Else {People [I] = new person (field [0], integer. parseint (field [1]), double. parsedouble (field [2]) ;}// Save the input data to "people. dat. Printwriter out = new printwriter (New bufferedwriter (New filewriter ("People. dat"); writedata (people, out); // close the stream. Out. Close (); // read data from the file "People. dat. Bufferedreader in = new bufferedreader (New filereader ("People. dat"); person [] inpeople = readdata (in); // close the stream. In. Close (); // output the data read from the file. For (INT I = 0; I <inpeople. length; I ++) {system. out. println (inpeople [I]);} catch (ioexception exception) {system. err. println ("ioexception") ;}// write all data to the output stream. Static void writedata (person [] P, printwriter out) throws ioexception {// Number of write records, that is, the number of people. Out. println (P. length); For (INT I = 0; I <p. length; I ++) {P [I]. writedata (out) ;}// read all data from the input stream. Static person [] readdata (bufferedreader in) throws ioexception {// obtain the number of records, that is, the number of people. Int n = integer. parseint (in. readline (); person [] P = new person [N]; for (INT I = 0; I <n; I ++) {P [I] = new person (); P [I]. readdata (in) ;}return P ;}} class person {private string name; private int age; private double salary; private string married; Public Person () {} public person (string N, int A, double S) {name = N; age = A; salary = s; married = "F";} public person (string N, int A, Dou Ble S, string m) {name = N; age = A; salary = s; married = m;} Public String getname () {return name;} public int getage () {return age;} public double getsalary () {return salary;} Public String getmarried () {return married;} // you can specify the output format. Public String tostring () {return getclass (). getname () + "[name =" + name + ", age =" + age + ", salary =" + salary + ", married = "+ Married +"] ";} // write a record, that is, a person's data to the output stream. Public void writedata (printwriter out) throws ioexception {// format the output. Out. println (name + ":" + age + ":" + salary + ":" + married) ;}// read a record from the input stream, that is, a person's data. Public void readdata (bufferedreader in) throws ioexception {string S = in. readline (); stringtokenizer T = new stringtokenizer (S, ":"); name = T. nexttoken (); age = integer. parseint (T. nexttoken (); salary = double. parsedouble (T. nexttoken (); married = T. nexttoken () ;}} package IO; import Java. io. ioexception; public class filestdread {public static void main (string [] ARGs) throws ioexception {int B = 0; char c = ''; system. Out. println (" Enter: "); While (C! = 'Q') {int A = system. in. read (); C = (char) A; B ++; system. out. println (char) A);} system. err. print ("counted" + B + "totalbytes. ") ;}} // read the input data until the Letter Q exists in the data, then package IO; import Java. io. *; public class iostreamexample {public static void main (string [] ARGs) throws ioexception {// 1. read a row of data: bufferedreader in = new bufferedreader (New filereader ("filestdread. java "); string S, S2 = New String (); While (S = in. Readline ())! = NULL) {S2 + = S + "";} In. close (); bufferedreader stdin = new bufferedreader (New inputstreamreader (system. in); system. out. print ("enter a line:"); system. out. println (stdin. readline (); // 2. read stringreader in2 = new stringreader (S2); int C; while (C = in2.read () from memory ())! =-1) {system. out. print (char) C);} // 3. format the memory input try {datainputstream in3 = new datainputstream (New bytearrayinputstream (s2.getbytes (); While (true) {system. out. print (char) in3.readbyte () ;}} catch (eofexception e) {system. err. println ("End of stream");} // 4. file input try {bufferedreader in4 = new bufferedreader (New stringreader (S2); printwriter out1 = new printwriter (New bufferedwriter (New filewriter ("iodemo. Out"); int linecount = 1; while (S = in4.readline ())! = NULL) {out1.println (linecount ++ ":" + S) ;}out1.close () ;}catch (eofexception e) {system. err. println ("End of stream");} // 5. receiving and saving data try {dataoutputstream out2 = new dataoutputstream (New bufferedoutputstream (New fileoutputstream ("data.txt"); out2.writedouble (3.14159); out2.writeutf ("that was Pi "); out2.writedouble (1.41413); out2.writeutf ("square root of 2"); out2.close (); datainputst Ream in5 = new datainputstream (New bufferedinputstream (New fileinputstream ("data.txt"); system. out. println (in5.readdouble (); system. out. println (in5.readutf (); system. out. println (in5.readdouble (); system. out. println (in5.readutf ();} catch (eofexception e) {Throw new runtimeexception (E);} // 6. random reading of file content randomaccessfile Rf = new randomaccessfile ("rtest. dat "," RW "); For (INT I = 0; I <10; I ++) {Rf. writedouble (I * 1.414);} RF. close (); Rf = new randomaccessfile ("rtest. dat "," RW "); RF. seek (5*8); RF. writedouble (1, 47.0001); RF. close (); Rf = new randomaccessfile ("rtest. dat "," R "); For (INT I = 0; I <10; I ++) {system. out. println ("value" + I + ":" + RF. readdouble ();} RF. close () ;}} package IO; import Java. io. *;/*** <p> * Title: Java advanced tips * </P> ** Zhang Feng * 1.0 */public class makedir Ectoriesexample {Private Static void fileattrib (file F) {system. out. println ("absolute path:" + F. getabsolutepath () + "readable attribute:" + F. canread () + "customizable attributes:" + F. canwrite () + "file name:" + F. getname () + "parent directory:" + F. getparent () + "current path:" + F. getpath () + "file length:" + F. length () + "Last Updated Date:" + F. lastmodified (); If (F. isfile () {system. out. println ("input is a file");} else if (F. isdirectory () {system. out. println (" The input is a directory ") ;}} public static void main (string [] ARGs) {If (ARGs. length <1) {ARGs = new string [3];} ARGs [0] = "D"; ARGs [1] = "test1.txt "; ARGs [2] = "test2.txt"; file old = new file (ARGs [1]), rname = new file (ARGs [2]); old. renameto (rname); fileattrib (old); fileattrib (rname); int COUNT = 0; Boolean del = false; If (ARGs [0]. equals ("D") {count ++; del = true ;}count --; while (++ count <args. leng Th) {file F = new file (ARGs [count]); If (F. exists () {system. out. println (F + "file already exists"); If (DEL) {system. out. println ("delete file" + F); F. delete () ;}} else {// if the object does not exist if (! Del) {f. mkdirs (); system. Out. println ("Create File:" + F) ;}} fileattrib (f );}}}

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.