[Android study notes] JAVA basics - I/O system

1. The target of I/O operations Read data
from the data source and write data to the data destination.
The source of the data and the destination of the data are multi-faceted.
The flow of I/O, input and output are relative to the java program:
input: data enters the program
Output : data is output from the program


The core class of the byte stream in IO

Common methods

/********************************************Byte Type**** ****************************/

InputStream (abstract class)

FileInputStream: read data from a hard disk file

int read(byte[] b,int off,int len);
/*
parameter
b: store the read data
off: read start offset
len: read the length of the most read at a time
return value
int: the length of this read
*/
OutputStream (abstract class)
FileOutputStream: Write data to the hard disk file
void write(byte[] b,int off,int len);
/*
parameter
b: the data to be written to the file
off: offset of the start of writing
len: the length of the written data
*/

Create two txt, from and to, write text in from

Write the following code:

import java.io.*;//Import all IO classes in java
class Test{
	public static void main(String args[]){
		FileInputStream fis = null;//Declare the input stream reference
		FileOutputStream fos = null;//Declare the output stream reference
		try{
			// Generate an object representing the input stream
			fis = new FileInputStream("d:/java/src/from.txt");
			// Generate an object representing the output stream
			fos = new FileOutputStream("d:/java/src/to.txt");
			// generate a byte array
			byte [] buffer = new byte[100];
			//Call the read method of the input stream object to read the data in from.txt
			int temp_length =fis.read(buffer,0,buffer.length);
			//Call the write method of the output stream object to write data to to.txt			
			fos.write(buffer,0,temp_length);
			String s = new String(buffer););//Restore byte to character
			//Call the trim method to remove the leading and trailing spaces and null characters from the string
			//For example, "abc def" will become "abc def" after using trim
			s.trim();
			
			System.out.println(s);//Print out
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}
operation result:
D:\JAVA\src>java Test
abcd

Be careful when using fis.read(buffer,0,buffer.length);

The sum of the offset and the read length cannot exceed the maximum length of the buffer array. The offset of off refers to the storage from the first position in the buffer. If the buffer has a maximum of 100 and is stored from the fifth, then The read length cannot be 100 but 95.


By Urien April 3, 2018 08:39:22

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325858940&siteId=291194637