java_IO write and read content to file code instance

  • 2021-07-09 08:22:01
  • OfStack

Write content to a file using OutStream () in java


package Stream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


public class OutStreamDemo01 {
	public static void main(String[] args) {
		// Define the file path, without which the file will be created automatically. If the path has folders, 1 Do have, folders will not be created automatically 
		String filename = "e:"+File.separator+"a"+File.separator+"b.txt";
		File file = new File(filename);
		String str = " These will all be written to the file ";
		byte[] b = str.getBytes();	// Convert a string to a number of bytes 
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);	// Instantiation OutpurStream
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}
		
		// Write 
		try {
			out.write(b);		// Write 
			out.close();		// Shut down 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Use InputStream () to read the contents of the file:


package Stream;
import java.io.*;;
public class InputStreamDemo01 {
	public static void main(String[] args) {
		File file = new File("e:"+File.separator+"a"+File.separator+"b.txt");
		byte[] b = new byte[(int)file.length()];// Definition byte Length of bytes 
		InputStream in = null;
		int len = 0;
		try {		// Handle exceptions 
			in = new FileInputStream(file);		// Instantiation FileInputstream Class 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();		// Output exception 
		}
		try {
			len = in.read(b);		// Read the contents of the specified file 
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(new String(b,0,len));// Converts a byte array to a string output from the specified file 0 Begin to len Byte end 
	}
}


Related articles: