我已经向文件写入了一个字符串,该字符串包含文件名及其长度。但是,当我从文件中提取该字符串,然后使用“空格”定界符将其拆分,然后尝试获取数字(即文件长度)时,它给出了NumberFormatException。有人可以帮忙吗?
import java.io.*;
public class DemoReadFromFile {
public static void main(String[] args) throws IOException,NumberFormatException {
byte[]b=new byte[100];int pos=0;byte[]data;
System.arraycopy("dest.txt".getBytes(), 0, b, 0, "dest.txt".length());
pos+="dest.txt".length()+1;
System.arraycopy(" ".getBytes(),0,b,pos," ".length());//1 byte here
pos+=1;
System.arraycopy("11".getBytes(), 0, b, pos, 2);
pos+=2;
System.arraycopy("\n".getBytes(), 0, b, pos, "\n".length());
pos+="\n".length();//1 byte here
pos+=37;
System.arraycopy("Hello World".getBytes(), 0, b, pos, "Hello World".length());
FileOutputStream fos=new FileOutputStream(new File("DemoRead.txt"));
fos.write(b);
fos.close();
//FileInputStream fis=new FileInputStream(new File("DemoRead.txt"));
byte[]rhead=new byte[50];
RandomAccessFile raf=new RandomAccessFile(new File("DemoRead.txt"),"rw");
raf.seek(0);
raf.readFully(rhead);
String[] tok=new String(rhead).split(" ");
for(String t:tok)
System.out.println(t);
System.out.println(tok[1]);
raf.seek(50);
Integer i=new Integer(tok[1]);
int len=Integer.parseInt(tok[1]);
data=new byte[i];
raf.readFully(data);
//System.out.println("Data is: "+new String(data));
}
}
答案 0 :(得分:0)
String[] tok=new String(rhead).split("[ \t\n]");