类型转换为题

romantic8899 2004-03-21 08:24:33
public class Test1
{
public static void main(String[] args)
{
int [] a={1,2,3,4,5,6,7,8};
byte [] s=new byte[a.length];
FileOutputStream f = new FileOutputStream("e:/a.txt");
f.write(???);//int[]与byte[]怎么转换才不至于出乱码
}
}
...全文
31 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
caiyanying732 2004-03-21
  • 打赏
  • 举报
回复
int [] a={1,2,3,4,5,6,7,8};
当然你在这里转为byte类型的话,还可以得到正确结果,但如果你改成这样:
int [] a={1000,2000,3000,4000,5000,6000,7000,8000};
结果就不同了
caiyanying732 2004-03-21
  • 打赏
  • 举报
回复
那就不一样,你再用DataInputStream 读出来看看是不是一样?
import java.io.*;
public class TestInputNumber
{
public static void main(String[] args) throws IOException
{
DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream("e:/a.txt")));
int j;
for(int i=0;i<8;i++) //不过这里要知道有多大:i<8,就是8个数;
System.out.println(in.readInt());
}
}
lu8088 2004-03-21
  • 打赏
  • 举报
回复
努力吧。我认为楼上的可以。我也不知道。
romantic8899 2004-03-21
  • 打赏
  • 举报
回复
这与强转的效果都一样啊...呵呵..同样都是乱码..
caiyanying732 2004-03-21
  • 打赏
  • 举报
回复
你不可以先转换
如:
for(int i=0;i<a.length;i++)
s[i]=(byte)a[i];
然后再存到文件里面吗?
其实你这样转换的话会掉好多信息的,日后你要恢复的话就可能得不到以前的数据。
看看我这个方法行不
import java.io.*;
public class Test1
{
public static void main(String[] args)
{
int [] a={1,2,3,4,5,6,7,8};
try{
DataOutputStream out=new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("e:/a.txt")));
for(int i=0;i<a.length;i++)
out.writeInt(a[i]);
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

62,615

社区成员

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

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