DataOutputStream out = new DataOutputStream(new
FileOutputStream("invoice1.txt"));
//定义要保存的数据数组。
double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
int[] units = { 12, 8, 13, 29, 50 };
String[] descs = { "Java T-shirt", "Java Mug",
"Duke Juggling Dolls",
"Java Pin", "Java Key Chain" };
//将prices,unites以及descs中的数据以Tab键为分割符保存在文件中。
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeChar('\t');
out.writeInt(units[i]);
out.writeChar('\t');
out.writeUTF(descs[i]);
out.writeChar('\t');
}
out.close();
以上是输出流的主要部分 将其写入文件中
可是为什么之后我打开文件确实一堆乱码(win7记事本打开):
@3齪W
= Java T-shirt @#?G?{ Java Mug @/?G?{
Duke Juggling Dolls @雲窺? Java Pin @趼廫(? 2 Java Key Chain
搞不懂这个问题 小白求大神解答
------解决方案--------------------
DataOutputStream输出的是底层字节表示,不是人能轻易看得懂的字符串。。
想以字符串形式输出方法有很多,数据不多的话先用一个StringBuilder拼接好再输出就行了,见下面代码。
public static void main(String[] args) throws IOException {
double[] prices = {19.99, 9.99, 15.99, 3.99, 4.99};
int[] units = {12, 8, 13, 29, 50};
String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls",
"Java Pin", "Java Key Chain" };
StringBuilder sb = new StringBuilder();
for (int i = 0; i < prices.length; i++) {
sb.append(prices[i]);
sb.append('\t');
sb.append(units[i]);
sb.append('\t');
sb.append(descs[i]);
sb.append('\t');
}
String str = sb.toString();
BufferedWriter bw = new BufferedWriter(new FileWriter("invoice.txt"));
bw.write(str);
bw.close();
}
------解决方案--------------------
把int,double转换成字符串的形式输出吧
out.writeBytes(String.valueOf(prices[i]));
out.writeChar('\t');
out.writeBytes(String.valueOf(units[i]));
out.writeChar('\t');
out.writeBytes(descs[i]);
out.writeBytes("\r\n");