JAVA operation IO flow four steps, simple and easy to remember

When we need to read content from a text file, or need to write content to a file, we need to use a stream in JAVA.

Stream includes input stream and output stream, read: use input stream, write: use output stream. In order to facilitate memory, it is divided into the following 4 steps.

One, read

1. New file input stream FileInputStream (byte stream, only one byte can be read, fis.read())

FileInputStream fis = new FileInputStram(filePath);

2. Create a new character input stream InputStramReader , (character stream, only one character can be read, isr.read())

InputStramReader isr = new InputStramReader(fis,"UTF-8");

3. Create a new buffered input stream BufferedReader (can read a line of characters)

BufferedReader br=new BufferedReader(isr);

4. Read the line

while((line=br.readLine())!=null){

System.out.println(line);

}

 

Two, write

1. Create a new file output stream FileOutputStream (byte stream)

FileOutputStream fos = new FileOutputStream(filePath);

2. Create a new character output stream OutputStreamWriter

OutputStreamWriter osw = new OutputStreamWriter(fos ,"UTF-8");

3. Create a new buffered output stream BufferedWriter (can write a line of characters)

BufferedWriter bw=new BufferedWriter(osw);

4, copy line

ArrayList<String> popertiesLines = new ArrayList<String>();

for(String line:popertiesLines){

  bw.write(line);

  bw.newLine(); //New line

}

 

Memory route (nonsense):

读:FileInputStream -> InputStreamReader -> BufferedReader -> br.readLine();

写: FileOutputStream-> OutputStreamWriter -> BufferedWriter -> bw.write(line);

Formula: Write and read out (all bleeding, too vicious), three-rate one operation


1. Reading and writing files, of course, first think of files (File), so file streams are used: FileInputStream, FileOutputStream

          File stream is used, where is the file path? So you need to specify the file path.

          Format: new FileInputStream(fileRealPath);

2. With the file stream, what operations should be done, read or write? Think of Reader, Writer. That is InputStreamReader, OutputStreamWriter

          Which file is read and written? So you need to specify the file stream created in step 1,

          What kind of characters are used for read and write operations? So you need to specify characters.

          格式: new InputStreamReader(fis, "utf-8");

3. Nothing is in place in one step, a certain amount of buffering is needed. Think of buffered, that is, BufferedReader, BufferedWriter

          Read buffer or write buffer? So you need to specify the "read and write stream" created in step 2.

          Format: new BufferedReader(isr);

4. The third-rate is ready and started.

        read? br.readLine();

        write? bw.write(line); Remember to wrap after writing a line: bw.newLine(); 

 

Example (modify a configuration file):

	/**
	 * 修改properties配置文件,保留原有注释。
	 * @param fileRealPath 文件绝对路径,
Linux: /root/iov_main/ly.mp.iov.login.main/bin
window:E:\后台开发工作空间\iov\ly.mp.iov.example.common\src\main\resources\domainname.properties
	 * @param keyName 键 ,如键不存在,则新增在后尾
	 * @param value 值
	 */
	public static boolean SetPropetyValue(String fileRealPath,String keyName,String value){
		ArrayList<String> popertiesLines = new ArrayList<String>();
		boolean hasKey=false;
		BufferedReader br=null;
		BufferedWriter bw=null;
		try {
			//1、读取配置文件
			FileInputStream  fis = new FileInputStream(fileRealPath);
			InputStreamReader isr = new InputStreamReader(fis, "utf-8");
			br = new BufferedReader(isr);
			String line = "";
			while ((line=br.readLine()) != null){
				// 找到该key,重新赋值(修改value)
				if(line.startsWith(keyName, 0)){
					hasKey=true;
					popertiesLines.add(keyName+"="+value);
					logger.info("SetPropetyValue----->line.startsWith:"+keyName+",line:"+line);
				}else{ //不是该key的行,直接追加
					popertiesLines.add(line);
				}
			}
			
			//全部没有找到,追加key
			if(!hasKey){
				popertiesLines.add(keyName+"="+value);
			}
			
			//2、重新写入配置文件
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileRealPath),"UTF-8");
			 bw= new BufferedWriter(osw);
			
			for(String lin:popertiesLines){
				bw.write(lin);
				bw.newLine();
			}
			bw.flush();
			
			return true;
		} catch (FileNotFoundException e) {
			logger.error("SetPropetyValue FileNotFoundException---->exception info:" + e.toString());
			return false;
		} catch (IOException e) {
			logger.error("SetPropetyValue IOException---->exception info:" + e.toString());
			return false;
		}finally{
			//关闭流
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}	

Knowledge points:

Separating slashes about the path.

Windows:

    "/" means parameter, "\"  means local path.

Linux and Unix:

    "/"  means path, "\" means escape, and "-" and "--" mean parameters.

 The internet:

    Since the network uses the Unix standard, the network path uses "/".

 

1、InputStream、OutputStream

Abstract class for handling byte streams

InputStream is the superclass of all classes of byte input streams, and generally we use its subclasses, such as FileInputStream.

OutputStream is the superclass of all classes of byte output streams, and generally we use its subclasses, such as FileOutputStream.

InputStream can read a byte from the source, so it is the lowest level.

 

2.InputStreamReader  OutputStreamWriter

Abstract class for handling character streams

InputStreamReader is a bridge from byte flow to character stream, it converts byte stream into character stream.

OutputStreamWriter is a bridge from character flow to byte stream, it converts character stream into byte stream.

 InputStreamReader encapsulates InputStream in it. It reads one character at a time in a higher-level way, and the character needs to be specified during initialization.

3.BufferedReader BufferedWriter

BufferedReader is extended from the Reader class to provide general buffered text reading, readLine reads a text line,

Read text from the character input stream and buffer individual characters to provide efficient reading of characters, arrays, and lines.

BufferedWriter is extended from the Writer class to provide general buffered text writing. newLine uses the platform’s own line separator,

Write text into the character output stream and buffer individual characters to provide efficient writing of single characters, arrays and strings.

BufferedReader is more advanced than InputStreamReader, it encapsulates the StreamReader class.

 

We all know that computers can only recognize 0 and 1, and data is stored in bytes.

    a. So in java, if we want to read a character from a file, we first need to have a file (data source), so we use the File class to formulate a file;

    b. Because the data in the computer is 0 and 1 codes, in bytes, the file object we specify needs to be converted into a byte stream first, so the InputStream class needs to be used;

    c. At this time, if you just read the file in bytes in java, it is enough. But if you want to read the file with characters, you also need to encode the byte stream in a certain way, because different characters use different encoding methods, if you still use the byte stream, it may not reach our expectations. The desired effect. We can specify the character encoding method, which is specified and instantiated in the constructor of the InputStreamReader related class. By default, it is the Unicode encoding method. At this point, we have used InputStreamReader.

    d. After the above three steps, we can already read a character from the file, but reading only one character at a time cannot meet our needs for reading big data. At this time, BufferedReader comes in handy. From the Buffer in the name, we can infer that it has a buffering effect. The fact is that it can read multiple characters at a time, and the number of characters read at a time can be set freely.

 

 

 

Guess you like

Origin blog.csdn.net/u012660464/article/details/81877527