2016-02-25 121 views
0

我有以下文件超過了確定的大小,我想減少它,但是我感興趣的是文件的最後一行,所以我想刪除第一行直到大小等於允許的大小,從一個特定位置開始將文件複製到另一個文件

有沒有辦法在java中做到這一點?

+0

你想要做到這一點或重寫文件的解決方案是好嗎? –

+0

任何建議是受歡迎的 – rainman

+0

這個答案看起來不錯:http://stackoverflow.com/questions/14280385/file-truncate-operation-in-java – wolfram77

回答

3

試試這個:

long MAX_FILE_SIZE = 512; 

try(RandomAccessFile file = new RandomAccessFile("Path to inputfile", "r")) 
{ 
    long fileSize = file.length(); 

    long readStartPosition = fileSize - MAX_FILE_SIZE; 
    if(readStartPosition < 0) 
    { 
     readStartPosition = 0; 
    } 

    file.seek(readStartPosition); 

    try(OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("Path to outputfile"))) 
    { 
     byte[] buffer = new byte[1024]; 
     for(int bytesRead = file.read(buffer); bytesRead != -1; bytesRead = file.read(buffer)) 
     { 
      outputStream.write(buffer, 0, bytesRead); 
     } 
    } 
} 
catch(Throwable t) 
{ 
    System.out.println(t);; 
} 

或者這一點,如果你想保持相同的文件:

long MAX_FILE_SIZE = 512; 

try(RandomAccessFile file = new RandomAccessFile("Path to inputfile", "rw")) 
{ 
    long fileSize = file.length(); 

    long readStartPosition = fileSize - MAX_FILE_SIZE; 
    if(readStartPosition < 0) 
    { 
     return; 
    } 

    long writePosition = 0; 
    byte[] buffer = new byte[1024]; 

    file.seek(readStartPosition); 
    for(int bytesRead = file.read(buffer); bytesRead != -1; bytesRead = file.read(buffer)) 
    { 
     long currentPosition = file.getFilePointer(); 

     file.seek(writePosition); 
     file.write(buffer, 0, bytesRead); 

     writePosition += bytesRead; 

     file.seek(currentPosition); 
    } 

    long newSize = file.length() - readStartPosition; 
    file.setLength(newSize); 
} 
catch(Throwable t) 
{ 
    System.out.println(t);; 
} 

注:這兩個例子都寫在我的頭頂,但他們應該工作。至少你得到了它的竅門。

相關問題