2014-09-10 63 views
0

我的问题很清楚。根据当前API,我们可以删除整个文件或删除文件的全部内容。但我的需求只是从文件中删除固定数量的字节(数据)。如果我有大小30MB的文件。我想删除2MB的数据(从起始位置而不是从结束位置)。所以我的文件将减少到28MB。在此先感谢从java或android中删除固定数量的数据文件

+0

我没不要尝试任何东西......因为这个概念在C语言中是可能的,但在java中不可能。 – Moses 2014-09-10 14:07:06

+0

@SagarPilkhwal:我只能使用一个文件。因为在另一个线程中,我将一些数据添加到此文件。我的文件大小超过了限制。所以我必须从起始位置删除一些数据 – Moses 2014-09-10 14:09:05

+0

这很好。你可以给一些代码从文件 – Moses 2014-09-10 14:27:54

回答

0

使用FileChannel.truncate(n)将文件修剪到指定的大小n。

  long n = 4096; 

     File file = new File("FILE_PATH"); 
     RandomAccessFile raf = new RandomAccessFile(file, "rw"); 
     FileChannel fc = raf.getChannel(); 

     fc.truncate(n); 
     fc.size() 
0

你应该看看RandomAccessFile

这将让你寻找到你想要的文件中的位置,但你可以删除或更新你想要的段。

编辑:

嗯,这里是一些代码:

public class MainClass { 

    /** 
    * @param args 
    * @throws IOException 
    * @throws InterruptedException 
    */ 
    public static void main(String[] args) throws IOException, InterruptedException { 

     long count = 5;//your desired size 
     File file = new File("C:\\Users\\Pedram\\Desktop\\file.dat"); 
     RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); 
     FileChannel fileChannel = randomAccessFile.getChannel(); 
     System.out.println("Before deleting: " + randomAccessFile.length()); 
     fileChannel.transferTo(count, fileChannel.size() - count, fileChannel);//write data from position(fileChannel.size() - count) to end of file from the orginal file 
     randomAccessFile.setLength(randomAccessFile.length() - count);//delete the unnecessary data 
     System.out.println("After deleting: " + randomAccessFile.length()); 
    } 

} 

诀窍内transferTo法规定,我们只是诱骗拉我们想要的东西出来呢

+0

嗨,你能提供任何源代码或示例为您的答案 – Moses 2014-09-10 15:18:10

+0

@Moses看到编辑的答案。 – Pedram 2014-09-10 16:49:16

+0

嘿谢谢,我会试试你的答案。 – Moses 2014-09-12 06:48:51

相关问题