JAVA小练习139——OutputStream的练习

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


public class Demo139 {
	
	public static void main(String[] args) throws IOException {
		write3();
	}
	
	
	public static void write3() throws IOException{
		//找到目标文件
		File file = new File("F:\\a.txt");
		//建立数据的输出通道
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		//
		String data = "abcd";
		byte[] buf = data.getBytes(); // 97 98 99 100
		fileOutputStream.write(buf, 0, 2);  // 指定开始的索引值与字节个数写出。
		
		fileOutputStream.close();
		
		
		
	}
	
	
	//方式二: 先把数据转成字节数组然后再写出。
	public static void write2() throws IOException{
		//找到目标文件
		File file = new File("F:\\a.txt");
		//建立数据的输出通道
		FileOutputStream fileOutputStream = new FileOutputStream(file,true); //第二个参数为true时,写入文件数据就是以追加的形式写入的
		//准备数据, 把数据写出
		String str  = "\r\nhello world";
		//把字符串转成字节数组
		byte[] buf = str.getBytes();
		//把字节数组写出
		fileOutputStream.write(buf);
		//关闭资源
		fileOutputStream.close();
	}
	
	
	
	
	
	//方式一: 每次只能写 一个字节的数据 。 
	public static void write1() throws IOException{
		//找到目标文件
		File file = new File("f:\\a.txt");
		//建立数据的输出通道
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		//把数据写出
		fileOutputStream.write('h');
		fileOutputStream.write('e');
		fileOutputStream.write('l');
		fileOutputStream.write('l');
		fileOutputStream.write('o');
		//关闭资源
		fileOutputStream.close();
	}

}

猜你喜欢

转载自blog.csdn.net/Eric_The_Red/article/details/91972568