源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-08-12 07:32 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java将字符串写入文本文件代码示例
[b]一、Filewriter与File——-将字符串写入文本文件[/b]
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(); }
 }
[b]二、InputStream与OutputStream 输入与输出串流[/b]
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() ;
}
[b]三、ObjectOutputStream与ObjectInputStream[/b] ObjectOutputStream将Java对象的基本数据类型和图形写入OutputStream。可以使用ObjectInputStream读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。 [b]将序列化的对象写入文件[/b] 1、将序列化的对象写入文件 [code]FileOutputStreamfileStream=newFileOutputStream(“Myobject.ser”);//不存在则自动创建[/code] 2、创建ObjectOutputStream [code]ObjectOutputStreamos=newObjectOutputStream(fileStream);[/code] 3、写入对象 [code]os.writeObject(one);//one是一个对象实例的引用名[/code] 4、关闭ObjectOutputStream [code]os.close[/code] ObjectInputStream用于解序列化 [b]解序列化[/b] 1、创建FileInputStream [code]FileInputStreamfileStream=newFileInputStream(“MyObject.ser”);[/code] 2、创建ObjectInputStream [code]ObjectInputStreamos=newObjectInputStream(fileStream);[/code] 3、读取对象 [code]Objectone=os.readObject();[/code] 4、转换对象类型 Modelelf=(Model)one;//Model是one对象的类名称 5、关闭ObjectInputStream [code]os.close();[/code] [b]总结[/b] 以上就是本文关于Java将字符串写入文本文件代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部