gpt4 book ai didi

java - 尝试将数组转换为文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 07:16:13 25 4
gpt4 key购买 nike

我在将数组获取到字符串中的文本文件时遇到问题。到目前为止我的代码:

public class ArrayList 
{

public static void main(String[] args) throws IOException
{

int myArray [] = new int [20];

for (int i = 0 ; i < 20 ; i++) {
myArray [i] = (int) (Math.random () * 8);
System.out.print(myArray[i]);
String s1 = Arrays.toString(myArray);
System.out.println(s1);

s1 = "/Users/EricDkim/Desktop/FileIOTest/pfile.txt";
File f = new File(s1);
FileOutputStream fileOut = new FileOutputStream(f);

byte value = 0x63; //By adding 0x it reads it as hex
DataOutputStream dataOut = new DataOutputStream(fileOut);
//dataoutputstream is used to write primitive java
//data types (byte, int, char, double) and strings are to a file or a socket
dataOut.writeByte(value);

//creates 20 numbers
}

}

}

如何使用我创建的数组将其移动到文本文件?

最佳答案

使用 DataOutputStream#writeInt(int) 怎么样? :

for (int i = 0 ; i < myArray.length ; i++) { 
dataOut.writeInt(myArray[i]);
}

如果您想写为文本,请使用 BufferedWriter :

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOut));
for (int i = 0 ; i < myArray.length ; i++) {
bw.write(Integer.toString(myArray[i]));
}
bw.close();

不要忘记关闭流/编写器。

尝试

File f = new File(s1);
FileOutputStream fileOut = new FileOutputStream(f);
int myArray [] = new int [20];
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOut));
for (int i = 0 ; i < myArray.length ; i++) {
myArray [i] = (int) (Math.random () * 8);
bw.write(Integer.toString(myArray[i]));
bw.write(',');
}
bw.close();

文件的内容将是

0,5,1,3,4,0,0,3,0,6,7,6,4,1,1,6,0,6,7,4,

File f = new File(s1);
FileOutputStream fileOut = new FileOutputStream(f);
int myArray [] = new int [20];
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOut));
for (int i = 0 ; i < myArray.length ; i++) {
myArray [i] = (int) (Math.random () * 8);
}
bw.write(Arrays.toString(myArray));
bw.close();

文件的内容将是

[3, 3, 4, 4, 6, 1, 0, 2, 3, 5, 7, 7, 0, 5, 1, 2, 0, 4, 6, 4]

关于java - 尝试将数组转换为文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19936229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com