当前位置:主页 > 软件编程 > JAVA代码 >

java_IO向文件中写入和读取内容代码实例

时间:2021-01-09 11:14:49 | 栏目:JAVA代码 | 点击:

使用java中OutStream()向文件中写入内容

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) {
		//定义文件路径,没有该文件会自动创建,如果路径有文件夹,一定要有,不会自动创建文件夹
		String filename = "e:"+File.separator+"a"+File.separator+"b.txt";
		File file = new File(filename);
		String str = "这些都将写入文件中";
		byte[] b = str.getBytes();	//将字符串转换成字节数
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);	//实例化OutpurStream
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}
		
		//写入
		try {
			out.write(b);		//写入
			out.close();		//关闭
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

使用InputStream()读取文件中的内容:

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()];//定义byte字节的长度
		InputStream in = null;
		int len = 0;
		try {		//处理异常
			in = new FileInputStream(file);		//实例化FileInputstream类
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();		//输出异常
		}
		try {
			len = in.read(b);		//读取指定文件的内容
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(new String(b,0,len));//将字节数组转化成字符串输出指定文件从0开始到len字节结束
	}
}

您可能感兴趣的文章:

相关文章