我在使用字符串中的文本文件获取数组时遇到问题。 到目前为止我的代码:
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
}
}
}
我如何使用我创建的数组将其移动到文本文件?
答案 0 :(得分:1)
如何使用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]
答案 1 :(得分:0)
声明
File f = new File(s1);
FileOutputStream fileOut = new FileOutputStream(f);
DataOutputStream dataOut = new DataOutputStream(fileOut);
在for
循环之前的和循环结束时关闭游览流,如dataOut.close();
将内容写为文本时,请检查此编辑的代码。
public class ArrayList {
public static void main(String[] args) throws IOException {
int myArray[] = new int[20];
String s1 = "/Users/EricDkim/Desktop/FileIOTest/pfile.txt";
File f = new File(s1);
Writer fileOut = new FileWriter(f);
BufferedWriter dataOut = new BufferedWriter(fileOut);
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);
byte value = 0x63; // By adding 0x it reads it as hex
// dataoutputstream is used to write primitive java
// data types (byte, int, char, double) and strings are to a file or
// a socket
fileOut.write(Arrays.toString(myArray) + "\n");
// creates 20 numbers
}
dataOut.close();
}
}