Scanner class
1 reading from the keyboard
publicclass ScannerTest { publicstaticvoidmain(String[] args ) { new Scanner(System.in); System.out.println("请输出一个整数:"); int i = input.nextInt(); System.out.println("你输入的整数是:" + i); }}
Results:
2 reading from a string
publicclass ScannerTest2 { publicstaticvoidmain(String[] args ) { //这里的\r\n是换行符,Linux下其实只用\n即可 new Scanner("hello\r\nworld\r\n"); //循环读取,hasNext()方法和集合框架里面的一样使 while(input.hasNext()) { //每次读取一行,别的读取方法见API,比较简单 String s = input.nextLine(); System.out.println(s); } }}
Results
3 reading from a file
Public classSCANNERTEST3 { Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt"; File f =NewFile (path); Path path2 = F.topath (); Scanner input =NULL;Try{//Construct scanner object from file, it is possible to produce an exceptioninput =NewScanner (path2); System. out. println (F.getabsolutepath ()); System. out. Print (Input.hasnext ()); while(Input.hasnext ()) {String s = input.nextline (); System. out. println (s); } }Catch(IOException e) {E.printstacktrace (); }finally{Input.close (); } }}
Result diagram:
It can be seen that the encoding format is different, for Chinese scanning output is garbled.
There is one more thing to note:
Public classSCANNERTEST3 { Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt"; File f =NewFile (path); Scanner input =NULL;Try{//Construct scanner object from file, it is possible to produce an exceptioninput =NewScanner (f); System. out. println (F.getabsolutepath ()); System. out. Print (Input.hasnext ()); while(Input.hasnext ()) {String s = input.nextline (); System. out. println (s); } }Catch(IOException e) {E.printstacktrace (); }finally{Input.close (); } }}
When I do the test, I use the same method as above to read the file, and I can't read the contents of the file. I don't know why! Please everyone who knows the words, the generous enlighten ~~~!!
PrintWriter class
4 Writing content to a file
Public classPrintwritertofile { Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt";//Create file ObjectFile File =NewFile (path); PrintWriter p =NULL;Try{//This constructor can also be used to pass other objects, refer to the API documentationp =NewPrintWriter (file);//write a line to the file, plus the print () and printf () methodsP.println ("If one day I return to the past."); P.println ("Back to the original me."); P.println ("Are you going to think I'm good?");//Refresh streamP.flush (); }Catch(FileNotFoundException e) {E.printstacktrace (); }finally{P.close (); } }}
Result diagram:
Similar to PrintWriter, there is a PrintStream class, where the printwriter example is because the text file is human-readable
binary files (byte mode) require a specialized program to read
Some people may ask: FileOutputStream, FileWriter can write files, then why do you need PrintWriter and PrintStream class
If you look at the API documentation, you can see that the simple character write stream and byte write flow operations are mostly done in arrays
The processing of files is very inconvenient, and printwriter and printstream solve this problem well, provide print () and other methods
Also, PrintWriter and PrintStream are created directly for non-existent file objects, if there is already a file object
They will overwrite the original file without adding a method
It's also easy to solve the problem, look at the API documentation
PrintWriter has a constructor method PrintWriter (writer out), which is the ability to pass in a writer object
PrintStream has a constructor method PrintStream (OutputStream out), which is the ability to pass in a OutputStream object
So that's what we're going to say.
New PrintWriter (New FileWriter (file,true))
New PrintStream (New FileOutputStream (file,true))
Data can be added and files processed more efficiently
5 Implementation of PrintWriter data append function
Public classPrintwriterappendfile { Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt";//Create file ObjectFile File =NewFile (path); PrintWriter p =NULL;Try{//Use FileWriter to build PrintWriter objects for additionalp =NewPrintWriter (NewFileWriter (file,true)); P.println ("Wqnmglb This sentence is added to see no"); P.flush (); }Catch(IOException e) {E.printstacktrace (); }finally{//We'll be careful to close the flow, okay ^_^P.close (); } }}
Results:
System class support for IO
6 writes in the system class
publicclass SystemOutTest { publicstaticvoidmain(String[] args) { //别忘了,OutputStream是所有字节写入流的父类 out = System.out; try { //写入数据,只能是数组,所以用getBytes()方法 out.write("Hello,son of bitch!\r\n".getBytes()); catch (IOException e) { e.printStackTrace(); } }}
Results:
7 read in the System class
Public classsystemintest { Public Static void Main(string[] args) {//Don't forget InputStream is the parent of all byte input streamsInputStreaminch= System.inch; System. out. Print ("Please enter text:");byte[] buf =New byte[1024x768];intLen =0;Try{//The input data is guaranteed to the array, Len records the length of the inputLen =inch. read (BUF); }Catch(IOException e) {E.printstacktrace (); }//Print the data in the array as a stringSystem. out. println ("Your input is:"+NewString (BUF,0, Len)); }}
Results:
However, for the above scenario, if you enter Chinese, the output is garbled. Please pay attention to them. The reason for this is that bytes are read. If a character is read, there is no garbled condition.
In fact, for the current possible garbled situation, we can not be entangled. Because in the actual development process, will be basically a certain environment. For example: for Android development, Android above the default character encoding is Utf-8, you know, so even if there is garbled situation, the use of character format conversion CharSet class can be corrected. In web development, for example, you need to specify a character encoding format during web development, or GBK or UTF-8 but Utf-8 is recommended because the platform is good for portability.
8 using BufferedReader to achieve keyboard reading
Public classBufferedreaderfromscanner { Public Static void Main(string[] args) {BufferedReader BufferedReader =NewBufferedReader (NewInputStreamReader (System.inch)); System. out. Print ("Please enter text:");Try{String str = bufferedreader.readline (); System. out. println ("What you have entered is:"+ str); }Catch(IOException e) {E.printstacktrace (); }Try{//Close the stream, and the impatient will throw directlyBufferedreader.close (); }Catch(IOException e) {E.printstacktrace (); } }}
Results:
If there are any problems or errors please leave a message! Thank you ~ ~ ~ "Handshake"
The source is available for download later
Java IO Flow Details (iii)