1. Filewriter and File--Write strings to text files
public static void main(String[] args) { File f=new File("C://world.txt");//Create a new file object, and if it does not exist, create a file FileWriter fw; try { fw=new FileWriter(f); String str="hello world"; fw.write(str);//Write a string to the file under the specified path fw.close(); } catch (IOException e) { e.printStackTrace(); } }2. InputStream and OutputStream Input and OutputStream Streaming
public static void main(String args[]){File f= new File("C://world.txt") ;InputStream input = null ;// Prepare an input object try {input = new FileInputStream(f) ;byte b[] = new byte[1024] ;// All content is read into this array input.read(b) ;// Read content The read method in network programming will block input.close() ;System.out.println("Content is: " + new String(b)) ;} public static void main(String args[]){File f= new File("C://world.txt") ;// Declare File object OutputStream out = null ;// Prepare an output object out = new FileOutputStream(f) ;// Instantiate String str = "Hello World!!!" ;// Prepare a string byte b[] = str.getBytes() ;// Only output byte arrays, so change the string into a byte array out.write(b) ;// Output content, out.close() ;}3. ObjectOutputStream and ObjectInputStream
ObjectOutputStream writes the basic data types and graphics of Java objects to OutputStream. Objects can be read (refactored) using ObjectInputStream. The persistent storage of objects can be achieved by using files in streams.
Write serialized objects to a file
1. Write serialized objects to file
FileOutputStreamfileStream=newFileOutputStream(“Myobject.ser”);//不存在则自动创建
2. Create an ObjectOutputStream
ObjectOutputStreamos=newObjectOutputStream(fileStream);
3. Write to the object
os.writeObject(one);//one是一个对象实例的引用名
4. Close ObjectOutputStream
os.close
ObjectInputStream is used for deserialization
Serialization
1. Create FileInputStream
FileInputStreamfileStream=newFileInputStream(“MyObject.ser”);
2. Create an ObjectInputStream
ObjectInputStreamos=newObjectInputStream(fileStream);
3. Read the object
Objectone=os.readObject();
4. Convert object type
Modelelf=(Model)one;//Model is the class name of one object
5. Close ObjectInputStream
os.close();
Summarize
The above is all about Java's code example writing strings into text file. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you for your support to this site