代碼運行出來 文件里是亂碼而且 Arrays.toString()全是0
package RandomAccessFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
public class Randomaccessfile {
? ? ? ? public static void createfile(String filename){
? ? ? ? File file=new File(filename);
? ? ? ? if(!file.exists()){
? ? ? ? file.mkdir();
? ? ? ?
? ? ? ? }else{
? ? ? ? System.out.println("文件已存在");
? ? ? ? }
? ? ? ? }
?
? ? ??
? ? ? ?
? ? ? ??
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
? ? ? ? ? Randomaccessfile.createfile("demo\\r.dat");
? ? ? ? ? RandomAccessFile r=new RandomAccessFile("r.dat","rw");
? ? ? ? System.out.println(r.getFilePointer());
? ? ? ? ? for(int i=1;i<6;i++){
? ? ? ? ?r.writeDouble(i*1.422);//一個double類型占8個字節(jié)
? ? ? ? ? }
? ? ? ? ? System.out.println(r.getFilePointer());
? ? ? ? ? //把指針指到第四個數(shù)據(jù)后面
? ? ? ? ? r.seek(32);//r.seek(4*8);
? ? ? ? ? r.writeDouble(7*1.2212);//替換第五個數(shù)據(jù)
? ? ? ? ? System.out.println(r.getFilePointer());
? ? ? ??
? ? ? ? ? ? ?r.close();
? ? ? ? ? ? ?
? ? ? ? ? ? ?RandomAccessFile ra=new RandomAccessFile("r.dat","r");
? ? ? ? ? ? ?for(int i=1;i<6;i++){
? ? ? ? ? ? System.out.println("Value "+i+":"+ra.readDouble());;//一個double類型占8個字節(jié)
? ? ? ? ? ? ?}
? ? ? ? ? ? ?byte[] bytes=new byte[(int)ra.length()];
? ? ? ? ? ? ? ? ? ? ? ?ra.read(bytes); ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? System.out.print(Arrays.toString(bytes));
? ? ? ? ? ? ? ? ? ? ?
}
? ? ? ?
}
2017-04-20
那怎么會是亂碼呢?
2017-04-19
你的指針位置沒有移動
?RandomAccessFile ra=new RandomAccessFile("r.dat","r");
? ? ? ? ? ? ?for(int i=1;i<6;i++){
? ? ? ? ? ? System.out.println("Value "+i+":"+ra.readDouble());;//一個double類型占8個字節(jié)
? ? ? ? ? ? ?}
? ? ? ? ? ? ?byte[] bytes=new byte[(int)ra.length()];
遍歷文件之后指針在ra.length-1位置,要用ra.seek(0)初始化,才能重新讀取下面的內(nèi)容