Summary of IO (input and output) operations in Java (iii) _java

Source: Internet
Author: User
To tell you the truth, I don't really like the language of Java, although it is very powerful, there are many out-of-the-box APIs that can call
But I always feel like it makes simple things too complicated, and sometimes it gets lost.
It's not clear whether it's for writing, or for the language itself.
The first programming language I learned was Python, though not very deep.
But its simplicity and elegance have been unforgettable (er, it was two years ago ...). )
The second language I Touch is C, which gives me the feeling of being a pure, efficient and flexible
Instead of Java, write a bunch of vague code to achieve a small function
Frankly, if a person is learning something they are not interested in, it will be very tiring.
What supports me is that I have an unusual yearning for mobile development and I like Android very much, but the main language of Android is Java
Although I have studied for six months, but I have not been able to explain God horse Enterprise-level development in the end what are the things
All I want is to use programming as a kind of flirting in life, and if you want a function, do it, in the simplest possible way
Even my guess is that when it comes to future development, the technology of programming is like when everyone uses office.
So how hard are you to be a programmer?
You know, it's pretty scary for a man to put his inner interests above the real idea ...
Therefore, everyone should use their favorite, feel efficient way to do their most want to do
Well, having said so much, my purpose is actually only one
Am I going to tell you that I don't understand and don't want to understand Java's complicated garbage syntax?
I only use the simplest and most useful things ...
Java's previous IO writing I was too lazy to record, mainly the system class support for IO
If you think my code is not deep enough, then you spray it, but after the spray, what else can you do?

Now, step into the business ...
In this section, we'll talk about the use of scanner classes and PrintWriter classes.

Scanner class
Instance 1: Reading from the keyboard
Copy Code code as follows:

Import Java.util.Scanner;
public class Demo {
public static void Main (string[] args) {
Scanner input = new Scanner (system.in);
SYSTEM.OUT.PRINTLN ("Please output an integer:");
int i = Input.nextint ();
System.out.println ("The Integer you entered is:" + i);
}
}

The above demo is only read an integer, of course, and read floating-point numbers and other data types of methods, relatively simple, viewing the API can


Instance 2: Reading from a string

Copy Code code as follows:

Import Java.util.Scanner;
public class Demo {
public static void Main (string[] args) {
Here's \ r \ n is a line break, Linux in fact only use \ n can
Scanner input = new Scanner ("hello\r\nworld\r\n");
Loop read, the Hasnext () method is the same as the collection frame
while (Input.hasnext ()) {
It is simpler to read one line at a time and see the API in other ways.
String s = input.nextline ();
System.out.println (s);
}
}
}


Instance 3: Reading from a file

Copy Code code as follows:

Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.util.Scanner;
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);
Scanner input = null;
try {
To construct a scanner object from a file, it is possible to produce an exception
input = new Scanner (f);
while (Input.hasnext ()) {
String s = input.nextline ();
System.out.println (s);
}
catch (FileNotFoundException e) {
E.printstacktrace ();
finally {
Input.close ();
}
}
}

Note here that creating a scanner object from a file must first have a file object, and of course you can use an anonymous object to create
In addition, you need to catch exceptions and close the file stream


PrintWriter class
Instance 4: Writing to a file

Copy Code code 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 {
Here constructors can also pass other objects, specific reference API documentation
p = new PrintWriter (file);
Writes a row to a file, in addition to the print () and printf () methods
P.println ("If one day I go back to the past");
P.println ("Back to the Original Me");
P.println ("Do you think I'm Good");
Refresh Stream
P.flush ();
catch (FileNotFoundException e) {
E.printstacktrace ();
finally {
P.close ();
}
}
}


Similar to PrintWriter, there is also a PrintStream class, where PrintWriter is used as an example because of the human readability of text files
A binary file (Byte mode) requires a specialized program to read
Some people may ask: FileOutputStream, FileWriter can write files, then why need PrintWriter and PrintStream class
If you look at the API documentation, you can know that the former simple character write stream and byte write stream operations are mostly done with arrays
The refinement of the file is very inconvenient, and PrintWriter and printstream to solve the problem, provide print () and other methods
Also, PrintWriter and PrintStream are created directly if there are no file objects, if the existing file objects
They will overwrite the original file, but not add the method

It is also easy to solve the problem, and then look at the API documentation
PrintWriter has a construction method PrintWriter (Writer out), which is the ability to pass in Writer objects
PrintStream has a construction method PrintStream (OutputStream out), which means that the OutputStream object can be passed in
So we can write that.
New PrintWriter (New FileWriter (file,true))
New PrintStream (New FileOutputStream (file,true))
It can increase data and process files more efficiently, as shown in the following code demonstration

Example 5: Implementing PrintWriter Data-appending functionality

Copy Code code 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 PrintWriter object with FileWriter method, implement Append
p = new PrintWriter (new FileWriter (file,true));
P.println ("Ni This sentence is appended to see not");
P.flush ();
catch (IOException e) {
E.printstacktrace ();
finally {
We're going to close the stream carefully, okay ^_^.
P.close ();
}
}
}

See, this will achieve the additional effect, the last line is


System class support for IO
the write in the instance 6:system class

Copy Code code as follows:

Import java.io.IOException;
Import Java.io.OutputStream;
public class Demo {
public static void Main (string[] args) {
Don't forget, OutputStream is the parent class for all byte write inflow
OutputStream out = System.out;
try {
Write data, only arrays, so use the GetBytes () method
Out.write ("hello,bitch! \ r \ n ". GetBytes ());
catch (IOException e) {
E.printstacktrace ();
}
}
}

Note that this is just a confirmation of System.out's overwrite behavior.
If you want to learn about IO, the polymorphism of the entire IO system needs to be understood to be very comfortable.


the read in the instance 7:system class

Copy Code code as follows:

Import java.io.IOException;
Import Java.io.InputStream;
public class Demo {
public static void Main (string[] args) {
Don't forget InputStream is the parent class for all byte input streams
InputStream in = system.in;
System.out.print ("Please enter text:");
byte[] buf = new byte[1024];
int len = 0;
try {
Guarantees the entered data to the array, Len records the length of the input
Len = In.read (BUF);
catch (IOException e) {
E.printstacktrace ();
}
Print data in an array as a string
SYSTEM.OUT.PRINTLN ("Your input is:" + new String (Buf,0,len));
}
}

Look, you can get content from the keyboard and print it.


Note that the size of the array here is 1024 bytes
Once you have entered more than 1024 bytes of data, the content will be intercepted, so this program has limitations
And, one Chinese occupies two byte, the input Chinese sometimes can be accidentally intercepted
Believe me, every program is written by myself compiled ~!!!
Example 8: Using BufferedReader to achieve keyboard reading

Copy Code code 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 ("Please enter text:");
try {
String str = b.readline ();
SYSTEM.OUT.PRINTLN ("You entered is:" + str);
catch (IOException e) {
E.printstacktrace ();
}
Loop Read mode
/*
while (true) {
System.out.print ("Please enter text:");
String str = NULL;
try {
str = B.readline ();
catch (IOException e) {
E.printstacktrace ();
}
End Loop if input over
if ("Over". Equals (str)) {
Break
}
SYSTEM.OUT.PRINTLN ("You entered is:" + str);
}
*/
try {
Turn off the stream, and the impatient is just throwing
B.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}

The advantage of doing this in relation to the previous method is that you don't care about the size of the array
BufferedReader one of the most important methods is ReadLine (), which reads a row at a time

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.