简体   繁体   中英

Using DataOutputStream to save a file, the how to out write the list<String>

I want to use DataOutputStream to get a file named"saved.txt". here are the codes:

import java.io.IOException;
import java.io.DataOutputStream;
import java.util.List;
import java.util.ArrayList;
import java.io.FileOutputStream;



public class ObjectOutputStreamTest {
public static void main(String[] args){
    int number1=5;
    double number2=10.3;
    String string="a string";
    List<String> list=new ArrayList<>();
    list.add("a");
    list.add("a");

    try{
        DataOutputStream out= new DataOutputStream(new       FileOutputStream("saved.txt"));

        out.writeInt(number1);
        out.writeDouble(number2);
        out.writeBytes(string);
        out.write(list);
    } catch( IOException e) {
        e.printStackTrace();
    }
    }


    }

But there is error at out.write(list); , the error is: The method write(int) in the type DataOutputStream is not applicable for the arguments (List). So how to correct this error? Thank you for any suggestion and answers.

DataOutputStream is for writing values in a binary format that can be read again by DataInputStream . Quoting the javadoc:

A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

It is not for writing a .txt file. Use a PrintWriter for that.

Try using PrintWriter and FileWriter --

public static void main(String[] args) {
    int number1 = 45;
    double number2 = 10.3;
    String string = "a string";
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("a");

    try {

      FileWriter fileWriter = new FileWriter("M:\\saved.txt");

      PrintWriter out = new PrintWriter(fileWriter);

      out.write(((Integer)number1).toString());
      out.println();
      out.write(string);
      out.println();
      out.write(((Double)number2).toString());
      out.println();
      for (String string2 : list) {
        out.write(string2);

      }
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM