【发布时间】:2018-12-06 02:31:02
【问题描述】:
我已将一个字符串写入文件,其中包含文件名及其长度。但是当我从文件中提取该字符串,然后使用“空格”分隔符将其拆分,然后尝试获取数字(即文件长度)时,它会给出 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));
}
}
【问题讨论】:
-
您是否尝试打印
new String(rhead)以查看其中的内容? -
你的 tok[1] 包括你应该摆脱它的行尾。 (\n) 使用 String[] tok=new String(rhead).split("\\s+");
标签: java numberformatexception