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

这篇文章将为大家详细讲解有关如何使用java中OutStream()向文件中写入内容,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

汉中网站建设公司创新互联,汉中网站设计制作,有大型网站制作公司丰富经验。已为汉中1000多家提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的汉中做网站的公司定做!

使用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中OutStream()向文件中写入内容”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


网站题目:如何使用java中OutStream()向文件中写入内容
本文网址:http://myzitong.com/article/jchdhd.html