当前位置: 移动技术网 > IT编程>开发语言>Java > Java将字符串写入文本文件代码示例

Java将字符串写入文本文件代码示例

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

一、filewriter与file——-将字符串写入文本文件

public static void main(string[] args) {
     file f=new file("c:\\world.txt");//新建一个文件对象,如果不存在则创建一个该文件
     filewriter fw;
     try {
       fw=new filewriter(f);
       string str="hello world";
       fw.write(str);//将字符串写入到指定的路径下的文件中
       fw.close();
       } catch (ioexception e) { e.printstacktrace(); }
 }

二、inputstream与outputstream 输入与输出串流

public static void main(string args[]){
	file f= new file("c:\\world.txt") ;
	inputstream input = null ;
	// 准备好一个输入的对象
	try {
		input = new fileinputstream(f) ;
		byte b[] = new byte[1024] ;
		// 所有的内容都读到此数组之中
		input.read(b) ;
		// 读取内容  网络编程中 read 方法会阻塞
		input.close() ;
		system.out.println("内容为:" + new string(b)) ;
	}
public static void main(string args[]){
	file f= new file("c:\\world.txt") ;
	// 声明file对象
	outputstream out = null ;
	// 准备好一个输出的对象
	out = new fileoutputstream(f) ;
	// 通过对象多态性,进行实例化
	string str = "hello world!!!" ;
	// 准备一个字符串
	byte b[] = str.getbytes() ;
	// 只能输出byte数组,所以将字符串变为byte数组
	out.write(b) ;
	// 将内容输出,
	out.close() ;
}

三、objectoutputstream与objectinputstream

objectoutputstream将java对象的基本数据类型和图形写入outputstream。可以使用objectinputstream读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。

将序列化的对象写入文件

1、将序列化的对象写入文件

fileoutputstreamfilestream=newfileoutputstream(“myobject.ser”);//不存在则自动创建

2、创建objectoutputstream

objectoutputstreamos=newobjectoutputstream(filestream);

3、写入对象

os.writeobject(one);//one是一个对象实例的引用名

4、关闭objectoutputstream

os.close

objectinputstream用于解序列化

解序列化

1、创建fileinputstream

fileinputstreamfilestream=newfileinputstream(“myobject.ser”);

2、创建objectinputstream

objectinputstreamos=newobjectinputstream(filestream);

3、读取对象

objectone=os.readobject();

4、转换对象类型

modelelf=(model)one;//model是one对象的类名称

5、关闭objectinputstream

os.close();

总结

以上就是本文关于java将字符串写入文本文件代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持

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

相关文章:

验证码:
移动技术网