今天就跟大家聊聊有關使用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??梢允褂肙bjectInputStream讀?。ㄖ貥嫞ο?。通過在流中使用文件可以實現對象的持久存儲。
將序列化的對象寫入文件
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怎么將字符串寫入文本文件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。