2013-04-27 101 views
1

我想写字符,双和整数回到我的二进制文件基础上我的字符串arraylist。但是,写完后,我再次读取二进制文件,它会产生错误。任何人都可以帮助我,我真的很感激它。写回数据到二进制文件

ArrayList<String>temp = new ArrayList<String>(); 
    for(int i = 0;i<temp.size();i++){ 
       String decimalPattern = "([0-9]*)\\.([0-9]*)"; 
       boolean match = Pattern.matches(decimalPattern, temp.get(i)); 
       if(Character.isLetter(temp.get(i).charAt(0))){ 
        os.writeChar(temp.get(i).charAt(0)); 
       } 
       else if(match == true){ 
        Double d = Double.parseDouble(temp.get(i)); 
        os.writeDouble(d); 
       }  
       else 
       { 
       int in = Integer.parseInt(temp.get(i)); 
       os.writeInt(in); 
       } 
      } 
      os.close(); 
     } 
+2

什么错误?你能告诉我们你如何阅读文件吗? – david 2013-04-27 18:28:39

+0

你开什么错误? – 2013-04-27 18:28:43

+4

问题是,你在你的二进制文件中随机写入'char','double'和'int',所以在读它时你不知道如何读取它,也就是说我必须先读一个'char',一个'double'还是'int'? – 2013-04-27 18:28:56

回答

2

这是一个非常简单的例子,它会告诉你如何阅读数据顺序

public void readFile(String absoluteFilePath){ 
    ByteBuffer buf = ByteBuffer.allocate(2+4+8) // creating a buffer that is suited for data you are reading 
    Path path = Paths.get(absoluteFilePath); 

    try(FileChannel fileChannel = (FileChannel)Files.newByteChannel(path,Enum.setOf(READ))){ 
     while(true){ 
      int bytesRead = fileChannel.read(buf); 
      if(bytesRead==-1){ 
       break; 
      } 
      buf.flip(); //get the buffer ready for reading. 
      char c = buf.asCharBuffer().readChar(); // create a view buffer and read char 
      buf.position(buf.position() + 2); //now, lets go to the int 
      int i = buf.asIntBuffer().readInt(); //read the int 
      buf.position(buf.position()+ 4); //now, lets go for the double. 
      double d = buf.asDoubleBuffer().readDouble(); 
      System.out.println("Character: " + c + " Integer: " + i + " Double: " + d); 
      buf.clear(); 
     } 
    }catch(IOException e){ 
     e.printStackTrace(); 
    }// AutoClosable so no need to explicitly close 
} 

现在,假设你总是写数据(字符, int,double)插入到文件中,并且没有机会将数据乱序或不完整为(char,int)/(char,double),您可以通过指定文件中的位置来随机读取数据,以字节测量,从那里到数据获取:

channel.read(byteBuffer,position); 

在你的情况下,数据的大小始终是14个字节作为2 + 4 + 8,以便所有的读位置将是14的倍数。

First block at: 0 * 14 = 0 
Second block at: 1 * 14 = 14 
Third block at: 2 * 14 = 28 

等..

enter image description here

类似的阅读,您也可以编写使用

channel.write(byteBuffer,position) 

同样,位置将是14

倍数这适用于FileChannel情况下这是一个超类的ReadableByteChannel其是用于读出的专用信道,WritableByteChannel其是用于写入的专用信道和SeekableByteChannel这可以做读写,但有点复杂。

当使用通道和ByteBuffer时,注意如何阅读。没有任何东西阻止我读取14个字节作为一组7个字符。虽然这看起来很可怕,但这会让您完全灵活地读取和写入数据。

+0

对不起,我忘记提到这一点,char,double和int的顺序必须基于一个txt文件。如果txt文件是char double和int。然后当你写数据回到二进制文件它也应该是char double int char double int ...(分隔线)等等。 – 14K 2013-04-27 19:28:57

+0

它是二进制的,所以*单独的行*将不可见。当你读回数据时,它取决于你如何以你想要的方式来表示它。如果txt文件具有任何顺序的数据,那么它必须有一些方法来识别下一个要读取的数据。也许一个代码标识下一步是什么 – 2013-04-28 01:17:35

+0

另外,当你使用通道编写时,你将创建一个** .bin **文件而不是一个txt文件。 – 2013-04-28 01:26:24