[英]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". 我想使用DataOutputStream获取名为“ 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);
但是在
out.write(list);
处有错误out.write(list);
, the error is: The method write(int) in the type DataOutputStream is not applicable for the arguments (List). ,错误是:类型DataOutputStream中的方法write(int)不适用于参数(列表)。 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
. DataOutputStream
用于以二进制格式写入值,该值可以由DataInputStream
再次读取。 Quoting the javadoc: 引用javadoc:
A data output stream lets an application write primitive Java data types to an output stream in a portable way.
数据输出流允许应用程序以可移植的方式将原始Java数据类型写入输出流。 An application can then use a data input stream to read the data back in.
然后,应用程序可以使用数据输入流来读回数据。
It is not for writing a .txt file. 它不是用于写入.txt文件。 Use a
PrintWriter
for that. 为此使用
PrintWriter
。
Try using PrintWriter and FileWriter -- 尝试使用PrintWriter和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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.