今天就跟大家聊聊有关使用Java怎么将字符串写入文本文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
一、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怎么将字符串写入文本文件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。