当前位置: 移动技术网 > IT编程>开发语言>Java > java_IO向文件中写入和读取内容代码实例

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

使用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字节结束
	}
}

以上所述是小编给大家介绍的java_io向文件中写入和读取内容详解整合,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网