Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何编写ArrayList<;双倍>;在Java中转换为文件_Java_Arraylist_Collections - Fatal编程技术网

如何编写ArrayList<;双倍>;在Java中转换为文件

如何编写ArrayList<;双倍>;在Java中转换为文件,java,arraylist,collections,Java,Arraylist,Collections,我想将ArrayList数组写入文件,这样当我双击文件时,文件就会打开,用户可以读取数据 我尝试了DataOutputStream&RandomAccessFile;这两种方法都很好,但当我双击文件时,它会显示不可读的数据 我试过这个: ArrayList<Double> larr=new ArrayList<Double>(); larr.add(5.66); larr.add(7.89); try{ FileOutputStream fos = new Fil

我想将
ArrayList
数组写入文件,这样当我双击文件时,文件就会打开,用户可以读取数据

我尝试了
DataOutputStream
&
RandomAccessFile
;这两种方法都很好,但当我双击文件时,它会显示不可读的数据

我试过这个:

ArrayList<Double> larr=new ArrayList<Double>();
larr.add(5.66);
larr.add(7.89);
try{
    FileOutputStream fos = new FileOutputStream("out.txt");
    DataOutputStream dos =  new DataOutputStream(fos);  
    for(Double d:larr)
        dos.writeDouble(d); 
    dos.close(); 
} catch(Exception ex) {
    ex.printStackTrace();
}
ArrayList larr=new ArrayList();
增加(5.66);
增加(7.89);
试一试{
FileOutputStream fos=新的FileOutputStream(“out.txt”);
DataOutputStream dos=新的DataOutputStream(fos);
用于(双d:larr)
可写双工(d);
dos.close();
}捕获(例外情况除外){
例如printStackTrace();
}
但现在的情况是,当我双击文件
out.txt
打开它时。它以不可读的形式出现。

我将使用获取人类可读的值到
out.txt
(并且我将亲自指定父文件夹;我喜欢用户的主目录)。另外,我更喜欢a和a方法。大概

public static void writeList(List<Double> al) {
    File f = new File(System.getProperty("user.home"), "out.txt");
    try (PrintWriter pw = new PrintWriter(f)) {
        for (Double d : al) {
            pw.println(d);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

1并请编程到
列表
界面。

这是因为您所说尝试使用的I/O流(
DataOutputStream
RandomAccessFile
)将数字视为二进制数据,而不是文本。您应该使用
打印流

例如:

PrintStream ps = new PrintStream(new File(filePath));
ps.println(5.25);
ps.close(); // Be sure to close the stream when you're done with saving the numbers

注意到一些熟悉的
ps.println(5.25)
System.out.println(5.25)
对控制台执行完全相同的操作。

@Lok-使用PrintWriter。。。。具体地说,
PrintWriter.print(double)
@ray我试过了,但没用;就像在Files.write中一样,它接受一个字符序列。@洛克:如果你遵循了发帖的基本规则,你会得到更多的帮助。例如,您应该提供一个。如果你希望得到合理数量的帮助,你需要提供代码供其他人查看,并表明你实际上已经尝试过研究某些东西,而不是在陷入困境后立即询问。@Stephan我试过
PrintWriter.print(双精度)
但您不认为它只会在控制台上打印,因为我的文件仍然是空的。@降档,但我也希望当我双击文件打开它时,它应该是人类可读的形式。
PrintStream ps = new PrintStream(new File(filePath));
ps.println(5.25);
ps.close(); // Be sure to close the stream when you're done with saving the numbers