Java IO Stream Learning notes

Source: Internet
Author: User

Import java.io.*;
Class hello{
public static void Main (string[] args) {
System.out.println (File.separator);
System.out.println (File.pathseparator);
}
}
"Run Results":

\

;

String filename= "D:" +file.separator+ "Hello.txt";
File F=new file (fileName);
if (f.exists ()) {
F.delete ();


File F=new file ("D:\\hello.txt");
Create a new file
F.createnewfile ();
Create a new Folder
F.mkdir ();
deleting files
F.delete ();


Lists all files (including hidden files) for the specified directory:
Listfiles output is the full path
String filename= "D:" +file.separator;
File F=new file (fileName);
File[] Str=f.listfiles ();
for (int i = 0; i < str.length; i++) {
System.out.println (Str[i]);
}
}else{
SYSTEM.OUT.PRINTLN ("File does not exist");
}

BYTE stream:

Pre-applied for a specified size space, but sometimes this space may be too small, sometimes too large, we need accurate size, so save space, then I
They can do this.
public static void Main (string[] args) throws IOException {
String filename= "D:" +file.separator+ "Hello.txt";
File F=new file (fileName);
InputStream in=new FileInputStream (f);
Byte[] b=new byte[(int) f.length ()];
for (int i = 0; i < b.length; i++) {
B[i]= (Byte) in.read ();
}
In.close ();
System.out.println (New String (b));
}
}


Sometimes we don't know how big the file is, in this case we need to judge whether the original file is at the end
public static void Main (string[] args) throws IOException {
String filename= "D:" +file.separator+ "Hello.txt";
File F=new file (fileName);
InputStream in=new FileInputStream (f);
Byte[] B=new byte[1024];
int count = 0;
int temp=0;
while ((Temp=in.read ())! = (-1)) {
b[count++]= (byte) temp;
}
In.close ();
System.out.println (New String (b));
}
Returns 1 when the end of the file is read. Normally, it will not return-1.

Character Stream:
Write:
public static void Main (string[] args) throws IOException {
String filename= "D:" +file.separator+ "Hello.txt";
File F=new file (fileName);
Writer out =new FileWriter (f);
String str= "Hello";
Out.write (str);
Out.close ();
}

In fact, this example has no difference in the previous example, but you can enter the string directly, without requiring you to convert the string into a byte array.

When you want to ask for additional content in the file, you can use the line that says the above declaration out:

Writer out =new FileWriter (f,true);

This way, when you run the program, you will find that the contents of the file become:

Hellohello if you want to wrap a file, you need to use "\ r \ n"

For example, change str to string str= "\r\nhello";

The contents of Str appended to this file will be wrapped.

Read:
public static void Main (string[] args) throws IOException {
String filename= "D:" +file.separator+ "Hello.txt";
File F=new file (fileName);
Char[] Ch=new char[100];
Reader read=new FileReader (f);
int temp=0;
int count=0;
while ((Temp=read.read ())! = (-1)) {
ch[count++]= (char) temp;
}
Read.close ();
System.out.println ("content is" +new String (Ch,0,count));
}


In fact, the byte stream in the operation of the time itself is not used in the buffer, is the direct operation of the file itself, but the character stream at the time of operation will be used in the buffer
is to manipulate the file through a buffer.

Readers can try to comment out the code that closes the last line of the program with the above byte stream and character stream, and then run the program to see it. You'll find that using the word stream.
, the content already exists in the file, but when the character stream is used, there is no content in the file, and the buffer will be refreshed at this time.


Outputstreramwriter the output character into a byte stream

InputStreamReader converting the input byte stream to a character stream

However, regardless of how it is done, it is finally saved in bytes in the file.

public static void Main (string[] args) {
Now output directly to the screen
System.out.println ("Hello");
File File = new file ("D:" + File.separator + "Hello.txt");
try{
System.setout (New PrintStream (new FileOutputStream (file));
}catch (FileNotFoundException e) {
E.printstacktrace ();
}
System.out.println ("These things can be seen in the file!") ");
}
}

"Run Results":

The console of eclipse output is hello. And then when we look at the Hello.txt file below the D drive, we'll see it in there: the content is visible in the file.

public static void Main (string[] args) {
BufferedReader buf = new BufferedReader (
New InputStreamReader (system.in));
String str = NULL;
System.out.println ("Please enter content");
try{
str = Buf.readline ();
}catch (IOException e) {
E.printstacktrace ();
}
System.out.println ("What you entered is:" + str);
}

BufferedReader can only accept buffers of character streams, because each text needs to occupy two bytes, so we need to system.in this byte input into a character input
Flow

BYTE stream: A read-in or read-out is a 8-bit binary.
Character Stream: A read-in or read-out is a 16-bit binary.
The principle of a byte stream and a character stream is the same, except that the units are handled differently. The suffix is stream is a byte stream, and the prefix is Reader,writer is a character stream.

The use of object flow requires the implementation of the serializable interface, or an error occurs.


With stream are byte stream, to reader, writer are character stream, of which 2 are acting as converters intputstreamreader and ontputstreamwriter, buffered stream
is to add the buffered, why to buffer the flow it:
Package low-level streams with buffered streams to speed up read and write


The original byte stream is not used in the buffer, but you can set it to a buffer stream.


Conversion flow: Inputstreamreader/outputstreamwriter, converting bytes into characters
Buffered buffer stream:: Bufferedinputstream,bufferedoutputstream,bufferedreader,bufferedwriter, is a processing stream with buffers, buffering
The main purpose of the district is to avoid dealing with the hard disk every time and improve the efficiency of data access.
Object flow: Objectinputstream,objectoutputstream, outputs the encapsulated object directly, rather than converting it into a string.

When do I use a transform stream?
1.
If you use a non-default encoding to save a file or read a file, you need to use the conversion stream, because the overloaded construction method of the byte stream has parameters in the specified encoding format, while Fielreader and FileWriter are the default encoded text files
Like what:

When we use the default GBK encoding to save text, the following 2 lines of code are actually the same effect,

New OutputStreamWriter (New FileOutputStream ("OUT.txt"))

New FileWriter ("OUT.txt")

When asked to save as other encodings such as UTF-8, write this

New OutputStreamWriter (New FileOutputStream ("OUT.txt"), "UTF-8")

And if you want to read a UTF-8 encoded text file, use the same

New InputStreamReader (New FileInputStream ("In.txt"), "UTF-8");

But not with new FileWriter ("In.txt")

Java IO Stream Learning notes

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.