Io (input and output) operations in java (3), iooutput

Source: Internet
Author: User
Tags truncated

Io (input and output) operations in java (3), iooutput
To be honest, I don't really like the Java language. Although it is very powerful, there are many ready-made APIs that can be called.
But I always feel that it makes simple things too complicated and sometimes gets lost.
I cannot tell whether it is for writing or for the language itself.
The first programming language I learned was Python, although I did not know much about it.
However, its simplicity and elegance are unforgettable (ER, actually two years ago ......)
The second language I came into contact with is C, which gives me the feeling of being pure, efficient, and flexible.
Instead of java, write a bunch of vague code to implement a small function.
Frankly speaking, if a person is learning something he is not interested in, it will be very tired.
Supporting me, I have an unusual yearning for mobile development, and I like Android very much. The main language for Android development is Java.
Although I have been studying for half a year, I still cannot explain what kind of enterprise development does Shenma have.
What I want is simply to treat programming as a flirt in my life. If I want a function, I will implement it in the simplest way possible.
Even my guess is that, when we develop in the future, the technology of programming is like everyone uses office.
How hard should you be a programmer?
You know, it's terrible for a person to put his or her own interests above his or her real thoughts ......
Therefore, everyone should use what they like and how efficient they are to do what they want most.
Well, I have only one purpose.
Will I tell you that I don't understand at all, and I don't want to understand the complicated garbage Syntax of java?
I only use the simplest and most useful things ......
I am too lazy to record the previous io writing methods in java, mainly because the System class supports IO.
If you think that the code I wrote is not deep enough, you can spray it. What else can you do after the injection?

Now, step into the topic ......
In this section, we will discuss the usage of the category class and the PrintWriter class.

Category
Instance 1: read from the keyboard
Copy codeThe Code is as follows:
Import java. util. collections;
Public class Demo {
Public static void main (String [] args ){
Wrote input = new partition (System. in );
System. out. println ("Please output an integer :");
Int I = input. nextInt ();
System. out. println ("the integer you entered is:" + I );
}
}

The preceding example only shows how to read an integer. Of course, there are methods to read floating point numbers and other data types. This is relatively simple. You can check the API.

 
Instance 2: read from string
Copy codeThe Code is as follows:
Import java. util. collections;
Public class Demo {
Public static void main (String [] args ){
// Here \ r \ n is a line break. in Linux, only \ n is used.
Inputs input = new inputs ("hello \ r \ nworld \ r \ n ");
// Read cyclically. The hasNext () method is the same as that in the set framework.
While (input. hasNext ()){
// Read a row at a time. For other reading methods, see API. This is relatively simple.
String s = input. nextLine ();
System. out. println (s );
}
}
}


Instance 3: read from a file
Copy codeThe Code is as follows:
Import java. io. File;
Import java. io. FileNotFoundException;
Import java. util. collections;
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
File f = new File (path );
Required input = null;
Try {
// Construct an upload object from a file. An exception may occur.
Input = new partition (f );
While (input. hasNext ()){
String s = input. nextLine ();
System. out. println (s );
}
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Finally {
Input. close ();
}
}
}

Note that a File object is required before you create a sequence object from a File. You can use an anonymous object to create a sequence object.
In addition, you must capture exceptions and close file streams.


PrintWriter class
Example 4: write content to a file
Copy codeThe Code is as follows:
Import java. io. File;
Import java. io. FileNotFoundException;
Import java. io. PrintWriter;
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
// Create a file object
File file = new File (path );
PrintWriter p = null;
Try {
// The constructor can also upload other objects. For more information, see the API documentation.
P = new PrintWriter (file );
// Write a row to the file, in addition to the print () and printf () Methods
P. println ("if one day I return to the past ");
P. println ("back to the original me ");
P. println ("Do you think I'm good ");
// Refresh the stream
P. flush ();
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Finally {
P. close ();
}
}
}


Similar to PrintWriter, there is also a PrintStream class, where the PrintWriter is used as an example because text files are human readable.
While binary files (in byte mode) require special programs to read
Some may ask: FileOutputStream and FileWriter can write files. Why do we still need the PrintWriter and PrintStream classes?
If you carefully read the API documentation, you can know that the former only supports character writing streams and byte writing streams.
It is inconvenient to refine the file, while PrintWriter and PrintStream solve this problem well and provide methods such as print ().
In addition, PrintWriter and PrintStream are directly created if no file object exists.
They will overwrite the original files, but there is no way to add them.

It's easy to solve this problem. Check the API documentation again.
PrintWriter has a constructor PrintWriter (Writer out), that is, it can pass in the Writer object.
PrintStream has a constructor PrintStream (OutputStream out), that is, it can pass in the OutputStream object.
Therefore, we can write it in this way.
New PrintWriter (new FileWriter (file, true ))
New PrintStream (new FileOutputStream (file, true ))
You can add data and process files more efficiently. See the following code example.

Instance 5: implement the data append function of PrintWriter
Copy codeThe Code is as follows:
Import java. io. File;
Import java. io. FileWriter;
Import java. io. IOException;
Import java. io. PrintWriter;
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
// Create a file object
File file = new File (path );
PrintWriter p = null;
Try {
// Construct the PrintWriter object using FileWriter to implement append
P = new PrintWriter (new FileWriter (file, true ));
P. println ("Nima is not added ");
P. flush ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
// Let's close the stream with caution, okay ^_^
P. close ();
}
}
}

Look, this will achieve the append effect. The last line is


IO support for the System class
Instance 6: write in the System class
Copy codeThe Code is as follows:
Import java. io. IOException;
Import java. io. OutputStream;
Public class Demo {
Public static void main (String [] args ){
// Do not forget that OutputStream is the parent class of all bytes written to the stream.
OutputStream out = System. out;
Try {
// Write data, which can only be an array. Therefore, use the getBytes () method.
Out. write ("Hello, bitch! \ R \ n ". getBytes ());
} Catch (IOException e ){
E. printStackTrace ();
}
}
}

Note: The overwrite behavior of System. out is confirmed here.
If you want to learn io well, the polymorphism in the entire io system needs to be clearly understood to be easy to learn.


Instance 7: read from the System class
Copy codeThe Code is as follows:
Import java. io. IOException;
Import java. io. InputStream;
Public class Demo {
Public static void main (String [] args ){
// Do not forget that InputStream is the parent class of all byte input streams.
InputStream in = System. in;
System. out. print ("Enter the text :");
Byte [] buf = new byte [1, 1024];
Int len = 0;
Try {
// Ensure that the input data is in the array, and the len records the input length.
Len = in. read (buf );
} Catch (IOException e ){
E. printStackTrace ();
}
// Print the data in the array as a string
System. out. println ("your input is:" + new String (buf, 0, len ));
}
}

You can get the content from the keyboard and print it.


Note that the array size is 1024 bytes.
Once the input data exceeds 1024 bytes, the excess content will be truncated, so this program has limitations.
In addition, a Chinese character occupies two bytes, and the input of Chinese characters is sometimes accidentally truncated.
Believe me, every program is compiled by myself ~!!!
Example 8: Use BufferedReader to read the keyboard
Copy codeThe Code is as follows:
Import java. io. BufferedReader;
Import java. io. IOException;
Import java. io. InputStreamReader;
Public class Demo {
Public static void main (String [] args ){
BufferedReader B = new BufferedReader (new InputStreamReader (System. in ));
System. out. print ("Enter the text :");
Try {
String str = B. readLine ();
System. out. println ("You entered:" + str );
} Catch (IOException e ){
E. printStackTrace ();
}
// Cyclic reading Method
/*
While (true ){
System. out. print ("Enter the text :");
String str = null;
Try {
Str = B. readLine ();
} Catch (IOException e ){
E. printStackTrace ();
}
// If the input is over, the loop ends.
If ("over". equals (str )){
Break;
}
System. out. println ("You entered:" + str );
}
*/
Try {
// Close the stream and throw it if you are impatient.
B. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}

Compared with the preceding method, this method does not have to worry about the array size.
One of the most important methods for BufferedReader is readLine (), which reads a row at a time.

Related Article

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.