首页 > 编程 > Java > 正文

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

2019-11-26 09:10:04
字体:
来源:转载
供稿:网友

使用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向文件中写入和读取内容详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表