Latest web development tutorials

Java stream (Stream), file (File) and IO

Java.io class package includes almost all operations of input and output needs. All of these stream classes represent the input source and output destination.

Java.io package streaming support a variety of formats, such as: basic types, objects, localized character sets and so on.

It can be understood as a sequence of a stream of data. Represents the input stream to read data from a source to a target output stream represents write data.

Java provides a powerful and flexible support for I / O, making it more widely used in file transfers and network programming.

However, this section describes the most basic and stream I / O related functions. We will learn through an example to these functions.


Read console input

Java console input completed by the System.in.

In order to obtain a binding character stream to the console, you can System.in wrapped in a BufferedReader object to create a stream of characters.

Here is the basic syntax to create a BufferedReader:

BufferedReader br = new BufferedReader(new 
                      InputStreamReader(System.in));

After BufferedReader object is created, we can use the read () method to read a character from the console, or read a string readLine () method.


Read more character input from the console

Read from BufferedReader object is a character you want to use read () method, which has the following syntax:

int read( ) throws IOException

Each call to read () method, which reads a character from the input stream and returns the character as an integer value. When the end of the stream returns -1. The method throws IOException.

The following program demonstrates the use read () method reads characters from the console continues until the user enters "q".

// 使用 BufferedReader 在控制台读取字符

import java.io.*;

public class BRRead {
   public static void main(String args[]) throws IOException
   {
      char c;
      // 使用 System.in 创建 BufferedReader 
      BufferedReader br = new BufferedReader(new 
                         InputStreamReader(System.in));
      System.out.println("Enter characters, 'q' to quit.");
      // 读取字符
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}

The above examples compiled results are as follows:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q

Reads a string from the console

Read from the standard input a string needs to use a BufferedReader readLine () method.

Its general format is:

String readLine( ) throws IOException

The following program reads and displays character rows until you enter the word "end".

// 使用 BufferedReader 在控制台读取字符
import java.io.*;
public class BRReadLines {
   public static void main(String args[]) throws IOException
   {
      // 使用 System.in 创建 BufferedReader 
      BufferedReader br = new BufferedReader(new
                              InputStreamReader(System.in));
      String str;
      System.out.println("Enter lines of text.");
      System.out.println("Enter 'end' to quit.");
      do {
         str = br.readLine();
         System.out.println(str);
      } while(!str.equals("end"));
   }
}

The above examples compiled results are as follows:

Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

JDK version 5 after we can also use Java Scanner class to get input console.

Console output

It has been introduced in the previous output of the console is done by print () and println (). These methods defined by the class PrintStream, System.out is a reference to the class object.

PrintStream inherited OutputStream class, and implements the method write (). Thus, write () can also be used to and from the console writes.

The simplest definition of PrintStream format write () are as follows:

void write(int byteval)

This method will lower octet byteval written to the stream.

Examples

The following example uses write () the character "A" and followed by a newline character output to the screen:

import java.io.*;

// 演示 System.out.write().
public class WriteDemo {
   public static void main(String args[]) {
      int b; 
      b = 'A';
      System.out.write(b);
      System.out.write('\n');
   }
}

Run the above example output "A" character in the output window

A

Note: write () method is not often used because print () and println () method is more convenient to use.


Reading and Writing Files

As described above, a stream is defined as a sequence of data. Input stream for reading data from the source to the target output stream for writing data.

The following is a description of the class hierarchy diagram input and output streams of.

The following will be discussed two important streams are FileInputStream and FileOutputStream:


FileInputStream

The stream for reading data from a file, its object can be used to create a new keyword.

There are several construction methods can be used to create objects.

You can use the string type file name to create an input stream object to read the file:

InputStream f = new FileInputStream("C:/java/hello");

You can also use a file object to create a stream object to read input files. We first have to use the File () method to create a file object:

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

InputStream object is created, you can use the following method to read the stream flow or perform other operations.

No. Method and Description
1 public void close () throws IOException { }
Closes this file input stream and releases any system resources associated with this stream. Throws IOException.
2 protected void finalize () throws IOException { }
This method clears the connection with the file. Ensure that no longer call its close method reference file input stream. Throws IOException.
3 public int read (int r) throws IOException {}
This method reads the specified bytes of data from the InputStream object. It returns an integer value. Returns the next byte of data, if you have to end it returns -1.
4 public int read (byte [] r ) throws IOException {}
This method reads bytes r.length length from the input stream. Returns the number of bytes read. If it is the end of the file -1 is returned.
5 public int available () throws IOException { }
Returns the next method invocation on this input stream without blocking by the number of bytes from the input stream read. Returns an integer value.

In addition to InputStream, there are some other input stream, for more details refer to the following links:


FileOutputStream

This class is used to create a file and write file data.

* If the stream open a file for output, the target file does not exist, then the stream will create the file.

There are two ways to create a constructor FileOutputStream object.

Use string type a file name to create an output stream object:

OutputStream f = new FileOutputStream("C:/java/hello") 

You can also use a file object to create an output stream to write files. We first have to use the File () method to create a file object:

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Create OutputStream object is complete, you can use the following method to write the stream flow or perform other operations.

No. Method and Description
1 public void close () throws IOException { }
Closes this file input stream and releases any system resources associated with this stream. Throws IOException.
2 protected void finalize () throws IOException { }
This method clears the connection with the file. Ensure that no longer call its close method reference file input stream. Throws IOException.
3 public void write (int w) throws IOException {}
This method takes the specified byte written to the output stream.
4 public void write (byte [] w )
The byte length of the specified array w.length written to the OutputStream.

OutputStream addition, there are some other output stream, for more details refer to the following links:

Examples

Here is a demonstration of InputStream and OutputStream usage examples:

import java.io.*;

public class fileStreamTest{

   public static void main(String args[]){
   
   try{
      byte bWrite [] = {11,21,3,40,5};
      OutputStream os = new FileOutputStream("test.txt");
      for(int x=0; x < bWrite.length ; x++){
         os.write( bWrite[x] ); // writes the bytes
      }
      os.close();
     
      InputStream is = new FileInputStream("test.txt");
      int size = is.available();

      for(int i=0; i< size; i++){
         System.out.print((char)is.read() + "  ");
      }
      is.close();
   }catch(IOException e){
      System.out.print("Exception");
   }	
   }
}

The above program creates a file test.txt, and the given number written in binary form of the document, while the output to the console.

Because it is written in binary code above, there may be garbled, you can use the following code examples to solve the garbage problem:

//文件名 :fileStreamTest2.java
import java.io.*;

public class fileStreamTest2{
	public static void main(String[] args) throws IOException {
		
		File f = new File("a.txt");
		FileOutputStream fop = new FileOutputStream(f);
		// 构建FileOutputStream对象,文件不存在会自动新建
		
		OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
		// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
		
		writer.append("中文输入");
		// 写入到缓冲区
		
		writer.append("\r\n");
		//换行
		
		writer.append("English");
		// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
		
		writer.close();
		//关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
		
		fop.close();
		// 关闭输出流,释放系统资源

		FileInputStream fip = new FileInputStream(f);
		// 构建FileInputStream对象
		
		InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
		// 构建InputStreamReader对象,编码与写入相同

		StringBuffer sb = new StringBuffer();
		while (reader.ready()) {
			sb.append((char) reader.read());
			// 转成char加到StringBuffer对象中
		}
		System.out.println(sb.toString());
		reader.close();
		// 关闭读取流
		
		fip.close();
		// 关闭输入流,释放系统资源

	}
}

Files and I / O

There are also classes on file and I / O, we also need to know:


The Java directory

Create a directory:

File class has two methods can be used to create a folder:

  • mkdir () method to create a folder, success, returns true, fails it returns false. Failure showed File object specified path already exists, or because the whole path does not exist, the folder can not be created.
  • mkdirs () method to create a folder and all of its parent folder.

The following example creates "/ tmp / user / java / bin" folder:

import java.io.File;

public class CreateDir {
   public static void main(String args[]) {
      String dirname = "/tmp/user/java/bin";
      File d = new File(dirname);
      // 现在创建目录
      d.mkdirs();
  }
}

Compile and execute the above code to create the directory "/ tmp / user / java / bin".

Note: Java on UNIX and Windows automatically according to the agreed resolution file path separator. If you use a separator in the Windows version of Java, (/), the path is still to be properly resolved.


Read directory

A directory is actually a File object that contains other files and folders.

If you create a File object and it is a directory, then a call isDirectory () method returns true.

By calling on the object list () method to extract a list of files and folders it contains.

The following example shows how to use the list () method to check the contents of a file contained in the folder:

import java.io.File;

public class DirList {
   public static void main(String args[]) {
      String dirname = "/tmp";
      File f1 = new File(dirname);
      if (f1.isDirectory()) {
         System.out.println( "Directory of " + dirname);
         String s[] = f1.list();
         for (int i=0; i < s.length; i++) {
            File f = new File(dirname + "/" + s[i]);
            if (f.isDirectory()) {
               System.out.println(s[i] + " is a directory");
            } else {
               System.out.println(s[i] + " is a file");
            }
         }
      } else {
         System.out.println(dirname + " is not a directory");
    }
  }
}

The above examples compiled results are as follows:

Directory of /tmp
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory