日期:2014-05-20 浏览次数:20990 次
//这样有错 class DataIO{ public static void writeFixedString(String name,int size,DataOutputStream out) throws IOException{ int i=0; char ch; while(i<size){ ch=0; if(i<name.length()){ ch=name.charAt(i); } out.writeChar(ch); i++; } } public static String readFixedString(int size,RandomAccessFile in) throws IOException{ int i=0; char ch; StringBuilder str=new StringBuilder(); while(i<size){ ch=in.readChar(); if(ch==0) break; i++; str.append(ch); } in.skipBytes(2*(size-i)); return str.toString(); } } /*改成这样问题是 if(ch=='0') break; 从文本中读取'0'字符赋予ch,可ch不会等于'0'了,ch=='0'永远为假,这是为什么? */ class DataIO{ public static void writeFixedString(String name,int size,DataOutputStream out) throws IOException{ int i=0; char ch; while(i<size){ ch=0; if(i<name.length()){ ch=name.charAt(i); } out.writeChar(ch); i++; } } public static String readFixedString(int size,RandomAccessFile in) throws IOException{ int i=0; char ch; StringBuilder str=new StringBuilder(); while(i<size){ ch=in.readChar(); if(ch=='0') break; i++; str.append(ch); } in.skipBytes(2*(size-i)); return str.toString(); } } //换成这样也不对,到底是为什么,好纠结 class DataIO{ public static void writeFixedString(String name,int size,DataOutputStream out) throws IOException{ int i=0; char ch; while(i<size){ ch=' '; if(i<name.length()){ ch=name.charAt(i); } out.writeChar(ch); i++; } } public static String readFixedString(int size,RandomAccessFile in) throws IOException{ int i=0; char ch; StringBuilder str=new StringBuilder(); while(i<size){ ch=in.readChar(); if(ch==' ') break; i++; str.append(ch); } in.skipBytes(2*(size-i)); return str.toString(); } }
class DataIO{ public static void writeFixedString(String name,int size,DataOutputStream out) throws IOException{ int i=0; char ch; while(i<size){ ch=0; if(i<name.length()){ ch=name.charAt(i); } out.writeChar(ch); i++; } } public static String readFixedString(int size,RandomAccessFile in) throws IOException{ int i=0; char ch; StringBuilder str=new StringBuilder(); while(i<size){ ch=in.readChar(); if(ch==0) break; i++; str.append(ch); } in.skipBytes(2*(size-i)); return str.toString(); } }
------解决方案--------------------
改成0的Assic 码,试试