如何将int数组中得值保存为一个文件,然后再一个一个从文件中读去出来保存到一个新数组中

yuantianwen 2007-03-29 06:30:36
如题
...全文
163 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
For_suzhen 2007-03-29
  • 打赏
  • 举报
回复
import java.io.*;
public class TestDataStreams{
public static void main(String[] args)
{
int[]a={1,2,3,4,5,6,7,8};
DataInputStream dis = null;
DataOutputStream dos = null;
File tempFile = new File("mytemp.dat");
if(tempFile.exists()){
//Exit
}
//write
try{
dos = new DataOutputStream(new FileOutputStream(tempFile));
for(int i=0;i < a.length;i++){
dos.writeInt(a[i]);
}
}catch(IOException ex)
{
//Message
}finally{
if(dos != null){
dos.close();
}
}
//read
int[]b;
try{
dis = new DataInputStream(new FileInputStream(tempFile));
for(int j=0;j < a.length;j++){
b[j] = dis.readInt()
}catch(IOException ex)
{
//Message
}finally{
if(dis != null){
dis.close();
}
}
}
}

}
For_suzhen 2007-03-29
  • 打赏
  • 举报
回复
而且你可以利用DataOutputStream 和 DataOutputStream里面的writeInt()和readInt()直接读取
For_suzhen 2007-03-29
  • 打赏
  • 举报
回复
你可以将int 型转成字符串.toString().然后用逗号分割类似写成一个csv文件,不过你保存成txt格式的,然后读的时候全处出来,直接放到一个string中,然后split成数组,再转成int
Integer.parseInt(str[i]);

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧