New string StringBuilder after "Java" input and output and JDK1.5

Source: Internet
Author: User

Input and output in Java is quite basic, in the Java major books and said, but the concept is often very complex, Java teacher stressed that students must thoroughly make every class, each method of meaning, in fact, we only focus on how to achieve a simple input and output effect. A small Java input and output on the web is all-encompassing, Mainly in the JDK1.5 introduced a new type of scanner input, and the previous BufferedReader can also complete the input operation, but also many experienced veteran to use their own set of habits put on the network, do not tell others how to modify. Here is an example of a thorough understanding of the input and output of Java, including the console, including the file, which is not difficult at all and is completely traceable.


I. BASIC OBJECTIVES

First there is a a.txt in C, there are some content


Next, I will write the following Java applet to illustrate the input and output of Java, the first time using Bufferreader and scanner to get user input line of things to illustrate the two methods of the same reason, scanner is only bufferreader improvement , followed by the use of scanner to get user input of a bunch of things, while stored in a dynamic array ArrayList inside, easy to operate later, not on-line programs do not know how to operate this heap of things. Dynamic array ArrayList do not understand, you can refer to my previous written "Java" Java Collections Class--java in the upgraded version of the data structure (click the Open link), Finally, read the above a.txt into the new Java string StringBuilder inside, then replace all the carriage returns in the string into spaces, and then output to the C-disk B.txt:



Second, the production process

1, the first is at the same time using Bufferreader and scanner to get the user input line of things to illustrate the two methods of the same reason, but before you have to introduce the following two packages:

Import Java.util.*;import java.io.*;
Scanner inside the util, bufferreader in Io, and the following dynamic arrays need these, before they start to work:

public static void Inputoneline () throws ioexception{//system.in actually correspond with System.out,// System.in refers to the user's input in the console, System.out is the output of the value console System.out.print ("Please enter a line of things:"); String inputstring= "";//scanner reads system.in, nextline () reads a line, that is, Inputstring=new Scanner (system.in) until the first carriage return is read. Nextline (); SYSTEM.OUT.PRINTLN ("You entered:" +inputstring); System.out.print ("Please enter a line of things:");//bufferedreader readline () inputstring=new BufferedReader (New InputStreamReader ( system.in)). ReadLine (); SYSTEM.OUT.PRINTLN ("You entered:" +inputstring);}

(1) It is worth noting that if the scanner scanner also has a next () method, this method is read to the first separator position, that is, if you encounter tab, space, carriage return, scanner will stop reading and writing, The buffer reader BufferedReader also has a read () method, which can read only one character and stop when it is read.

(2) Buffer reader BufferedReader must operate on the input stream, That is, the system.in must be converted into an input stream to be operated by the buffer reader, the scanner scanner is not used, you can operate on the system.in before, so scanner is a progressive

(3) Scanner inside there is also Nextint (), and so on, it means that if the user input is an int, you can automatically return this int, no more processing, generally no one uses these methods, because to increase the program's fault tolerance, robustness, everything is considered to be a string read in, The judgment of whether the number is then converted to a number.


2, followed by the use of scanner to get the user input a bunch of things, at the same time stored in a dynamic array ArrayList inside, easy to operate later.

public static void Inputmultiline () {//Create a dynamic array arraylist<string> inputstringarr=new arraylist<string> (); System.out.println ("Please enter a bunch of things, enter # end"); Scanner scanner=new Scanner (system.in);//This loop continues until the string read in is "#" interrupted//Because Java (as if not just in Java, in many languages), the string is an object, therefore, Can only use the Equals method to judge//==,!= compile error, the program is good, but run, because the object and object = = is to determine whether these two are string objects, not this! while (true) {string temp=scanner.nextline ();//If the string is not nothing, # # # (!temp.equals ("") &&!temp.equals ("#")) {// Then press it into the dynamic array inputstringarr.add (temp);} If it is # then interrupt loop if (Temp.equals ("#")) {break;}} System.out.println ("Just now, you entered something for" +inputstringarr);//If the dynamic array has a second function, then take it out and print it out if (inputstringarr.size () >1) { System.out.println ("The second behavior you entered:" +inputstringarr.get (1));}}

3, finally read the above a.txt into the new Java string StringBuilder inside, and then replace all the carriage returns in the string into spaces, and then output to the C-disk b.txt.

Here actually the scanner to scan things, from system.in to a file on the line, this method is set to the input and output of the file, so to run out of IO exception, as the buffer reader in the previous "Java" print stream and buffer reader to complete the input and output to the file operation (Click on the link to open it) has done, here does not do.

public static void Fileinputoutput () throws ioexception{//description I want to scan c:\a.txt, in the string \ must be escaped into \scanner scanner=new Scanner (new File ("C:\\a.txt")); StringBuilder filetostringtemp=new StringBuilder ("");//If there is another line? The Hasnext () method does not cause the cursor of the scanner scanner to jump down, so it can be used as a condition of judgement//if it jumps down, there is a phenomenon of interlaced not being read while (Scanner.hasnext ()) {// The StringBuilder does not have the overloaded operator + = number and can only be manipulated by the append () method, with the same result Filetostringtemp.append (Scanner.next ());//each line is read, then a newline is replaced, Scanner will not read the line in Filetostringtemp.append ("\ n");} Converting a StringBuilder to a string can also be done by its ToString. String Filetostring=new string (filetostringtemp); System.out.println (filetostring);//Convert all carriage returns to spaces, noting that ReplaceAll is a string that must be used to replace the original string,//It is not a void () method, We're done. Filetostring=filetostring.replaceall ("\ n", ""); System.out.println (filetostring);//Determine if the string is "#" to see the run result return true, this method is useful when judging the suffix name System.out.println ( Filetostring.endswith ("#"));//Print to a file with a print stream, where the specified file is specified by the file writer, so there is no problem with overwriting the output PrintWriter printwriter=new printwriter ( New FileWriter ("C:\\b.txt", true));//With the SYSTEM.OUT.PRINTLN () Console output method is similar to the good, but I am output to a file//the following line of code upside down to see you can understand PRIntwriter.println (filetostring);//the file print stream must be closed to finish the output, otherwise, the printed content will always be in memory only! Printwriter.close (); System.out.println ("The string filetostring has been exported to the b.txt of the C-drive. ");}
(1) Start by using the new string StringBuilder after JDK1.5 to continuously accept what is read from the file. This thing is better than string, frank string can also accept the string, and the program is shorter:

String a= ""; a+= "";
But this is said to be a lot more temporary variables for Java recycling, inefficient, encountered some long strings, The best use of JDK1.5 after the new string StringBuilder, this thing high efficiency, in addition JDK1.5 also added StringBuffer string, but this thing due to the inside of a thread-mutually exclusive protection mechanism, so efficiency is not StringBuilder high, but if there is multithreading operation the same string , using StringBuffer you do not have to write a thread-mutually exclusive code, what is the thread mutex, before the "Java" thread concurrency, mutual exclusion and synchronization (click the Open link) has been said.

(2) There is also a practical method of indexof and substring in the string, once in the "Java" intercept string in the first picture address (click Open link) did, no longer repeat.


Iii. Summary and Prospect

Thus, the entire program as follows, in the main function call above the three methods can be executed directly, these methods must be defined as a static method in order to be called:

Import Java.util.*;import java.io.*;p ublic class Scannertest {public static void Inputoneline () throws IOException {//Sys Tem.in actually correspond with System.out,//system.in refers to the user input in the console, System.out is the output of the value console System.out.print ("Please enter a line of things:"); String inputstring = "";//Scanner reads to System.in, nextline () reads a line, that is, reads the first carriage return inputstring = new Scanner (system.in). Nextline (); SYSTEM.OUT.PRINTLN ("You entered is:" + inputstring); System.out.print ("Please enter a line of things:");//BufferedReader ReadLine () similarly inputstring = new BufferedReader (New InputStreamReader ( system.in)). ReadLine (); SYSTEM.OUT.PRINTLN ("You entered:" + inputstring);} public static void Inputmultiline () {//Create a dynamic array arraylist<string> Inputstringarr = new arraylist<string> (); System.out.println ("Please enter a bunch of things, enter # end"); Scanner Scanner = new Scanner (system.in);//This loop continues until the string read in is "#" interrupted//Because Java (as if not just in Java, in many languages), the string is an object, therefore, Can only use the Equals method to judge//==,!= Compile error, the program is good, but run, because the object and object = = To determine whether these two are string objects, not this! while (true) {String temp = Scanner.nextline ();//If the string is not nothing, # # # (!temp.equals ("") &&!temp.equals ("#")) {//Then press it into the dynamic array inputstringarr.add (temp);} If it is # then interrupt loop if (Temp.equals ("#")) {break;}} System.out.println ("Just now, you entered something for" + Inputstringarr);//If the dynamic array has a second function, remove it and print it out if (Inputstringarr.size () > 1) { System.out.println ("The second behavior you entered:" + inputstringarr.get (1));}} public static void Fileinputoutput () throws IOException {//Description I want to scan c:\a.txt, in the string \ must be escaped to \scanner Scanner = new Scanner (New F Ile ("C:\\a.txt")); StringBuilder filetostringtemp = new StringBuilder ("");//If there is another line? The Hasnext () method does not cause the cursor of the scanner scanner to jump down, so it can be used as a condition of judgement//if it jumps down, there is a phenomenon of interlaced not being read while (Scanner.hasnext ()) {// The StringBuilder does not have the overloaded operator + = number and can only be manipulated by the append () method, with the same result Filetostringtemp.append (Scanner.next ());//each line is read, then a newline is replaced, Scanner will not read the line in Filetostringtemp.append ("\ n");} Converting a StringBuilder to a string can also be done by its ToString. String filetostring = new string (filetostringtemp); System.out.println (filetostring);//Convert all carriage returns to spaces, noting that ReplaceAll is a string that must be used to replace the original string,//It is not a void () method, It's done. Filetostring = Filetostring.replaceall ("\ n", ""); System.out.priNtln (filetostring);//Determine if the string is "#" to see the run result return true, this method is useful when judging the suffix name System.out.println (filetostring.endswith ("#")) ;//Print to a file with a print stream, where the specified file is specified by the file writer, so there is no problem with overwriting the output printwriter PrintWriter = new PrintWriter (New FileWriter ("C:\\b.txt", true);//With SYSTEM.OUT.PRINTLN () Console output method is similar to the good, but I am output to a file//the following line of code upside down you can understand printwriter.println (filetostring); You must close the file print stream to finish the output once, otherwise the printed content will always be in memory only! Printwriter.close (); System.out.println ("The string filetostring has been exported to the b.txt of the C-drive. ");} public static void Main (string[] args) throws IOException {Inputoneline (); Inputmultiline (); Fileinputoutput ();}}


New string StringBuilder after "Java" input and output and JDK1.5

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.