Simona
Simona

Reputation: 29

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.

Upvotes: 0

Views: 3237

Answers (2)

Ashish Patil
Ashish Patil

Reputation: 4624

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();
    }
  }

Upvotes: 0

Andreas
Andreas

Reputation: 159155

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.

Upvotes: 1

Related Questions