黑马程序员技术交流社区
标题:
发现一个问题关于读取byte数组
[打印本页]
作者:
贾存双
时间:
2012-7-17 05:17
标题:
发现一个问题关于读取byte数组
本帖最后由 贾存双 于 2012-7-17 07:39 编辑
import java.io.* ;
public class Demo{
public static void main(String args[])throws Exception{
File f = new File("e:" + File.separator + "io" + File.separator + "RandomAccessFile" + File.separator + "Random.txt") ;
RandomAccessFile raf = new RandomAccessFile(f,"rw") ;
String name = null ;
int age = 0 ;
name = "Jrain " ;
age = 22 ;
raf.writeBytes(name) ;
raf.writeInt(age) ;
name = "xiaojian" ;
age = 20 ;
raf.writeBytes(name) ;
raf.writeInt(age) ;
raf.close() ;
RandomAccessFile rf = new RandomAccessFile(f,"r") ;
byte b[] = new byte[8] ;
rf.skipBytes(12) ;
for(int i = 0;i<b.length;i++){
b
= rf.readByte() ;
}
/*for(byte i:b){
i = rf.readByte() ;
}*/ 如果把for循环改为foreach的形式,则byte数组读不到信息,是怎么回事???
int a = rf.readInt() ;
String str = new String(b) ;
System.out.println("读取到的姓名:" + str + "; 年龄:" + a) ;
}
}
这是普通的for循环打印出来的结果:
by.jpg
(9.62 KB, 下载次数: 108)
下载附件
2012-7-17 05:17 上传
这是用foreach打印出来的结果:
byte.jpg
(8.64 KB, 下载次数: 82)
下载附件
2012-7-17 05:14 上传
作者:
张_涛
时间:
2012-7-17 06:14
本帖最后由 张_涛 于 2012-7-17 06:18 编辑
import java.io.*;
public class Demo1 {
public static void main(String args[]) throws Exception {
File f = new File("Random.txt");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
String name = null;
int age = 0;
name = "Jrain ";
age = 22;
raf.writeBytes(name);
raf.writeInt(age);
name = "xiaojian";
age = 20;
raf.writeBytes(name);
raf.writeInt(age);
raf.close();
RandomAccessFile rf = new RandomAccessFile(f, "r");
byte b[] = new byte[8];
rf.skipBytes(12);
// for (int i = 0; i < b.length; i++) {
// b[i] = rf.readByte();
// System.out.println(b[i]);
// }
for (byte i : b) {
i = rf.readByte();
System.out.println(i);
}
//以下三行是我增加的内容。
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
int a = rf.readInt();
String str = new String(b);
System.out.println("读取到的姓名:" + str + "; 年龄:" + a);
}
}
运行结果:
120
105
97
111
106
105
97
110
0
0
0
0
0
0
0
0
读取到的姓名:
复制代码
这样,可以看出来,在foreach循环中对循环变量赋值并没有影响到原数组。原因如下:
使用foreach循环迭代数组、集合时,循环计数器只是保存了当前正在遍历的数组元素、集合元素的值,
并不是数组元素、集合元素本身,而只是一个复制副本
。因此不要对foreach循环的循环计数器(即循环变量)进行赋值,虽然语法允许,但是没有太大的意义,而且还可能出现错误。
另可以看看活动贴,了解更多:
http://bbs.itheima.com/thread-19543-1-1.html
作者:
贾存双
时间:
2012-7-17 07:41
谢谢 受教了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2