2014-10-17 72 views
0

我想將我的內容數據寫入文件的每個10kb文件。它看起來像這樣: enter image description here將數據更新到文件的每個字節數

我試了一下:

FileInputStream is; 
FileOutputStream out; 
File input = new File(filePath); 
int fileLength = input.length(); 
int len = 0; 
    while (len < fileLength){ 
     len += is.read(buff); 
     // write my data 
     out.write(data, 0, data.length); 
     // how to move is to read next 10kb??? 
    } 

我想反正是有光標閱讀機移動到字節的下一個量?或者我錯過任何東西?

更新:謝謝給@DThought,這裏是我的實現:

File input = new File(filePath); 
    long fileLength = input.length(); 
    byte[] data; 
    byte[] buff = new byte[data.length]; 
    long JUMP_LENGTH = 10 * 1024; 
    RandomAccessFile raf = new RandomAccessFile(input, "rw"); 

    long step = JUMP_LENGTH + data.length; 
    for (long i = 0; i < fileLength; i += step) { 
     // read to buffer 
     raf.seek(i); 
     raf.read(buff); 

     raf.seek(i); // make sure it move to correct place after reading 
     raf.write(data); 

    } 

    raf.close(); 

,效果不錯。

回答

2

例如,您可以將空數組或空格寫入該特定部分,因爲您無法跳轉到文件的特定內存並且無法避免10KB

FOR EXAMPLE

OutputStream os = new FileOutputStream(new File("D:/a.txt")); 
    byte[] emptyByte=new byte[10*1024]; 
    Arrays.fill(emptyByte, " ".getBytes()[0]);//Empty array 
    os.write(yourData,0,yourData.length-1); 
    os.write(emptyByte,0,emptyByte.length-1); 
    //Write after each data to leave space of 10KB 

我不知道究竟是如何設置的10KB等相比,它僅僅是一個例子,你可以用它來yours.I在文件的這一部分添加了空格。您可以根據您的要求實現它。 我認爲你不能直接跳轉到特定的內存地址,但你可以填充空數據。


我猜的RandomAccessFile#seek方法也可以幫助你通過DThought的建議,在此,但它是從該文件開始時所測所以敬請注意。