### Question:
FileBeheader { public static File chop(final File original, final long tailToKeep) { if (!original.isFile()) { throw new IllegalArgumentException("Cannot behead directories: " + original); } File truncatedFile = new File(original.getParentFile(), original.getName() + ".truncated"); FileChannel whole = null; FileChannel chopped = null; try { whole = new FileInputStream(original).getChannel(); chopped = new FileOutputStream(truncatedFile).getChannel(); long originalLength = original.length(); long lengthToKeep = originalLength < tailToKeep ? 0 : originalLength - tailToKeep; whole.transferTo(lengthToKeep, originalLength, chopped); } catch (IOException e) { throw new IllegalStateException("Cannot behead file due to inconsistent internal state.", e); } finally { Closer.close(whole, chopped); } boolean isRenamed = truncatedFile.renameTo(original); if (!(isRenamed)) { IllegalStateException renameException = new IllegalStateException("Cannot replace original with chopped file to: " + original); String originalPath = original.getAbsolutePath(); boolean isDeleted = original.delete(); if (isDeleted) { boolean isRenamedAgain = truncatedFile.renameTo(new File(originalPath)); if (!isRenamedAgain) { throw renameException; } } else { throw renameException; } } return original; }  static File chop(final File original, final long tailToKeep);  }### Answer:
@Test public void contentIsRemovedFromBeginning() throws IOException { File originalLog = cloneFile( templateLog ); long tail = originalLog.length() / 3; File choppedLog = FileBeheader.chop( originalLog, tail ); String firstLine = new Scanner( choppedLog ).nextLine(); assertThat( firstLine, not( containsString( "begin" ) ) ); assertThat( choppedLog.getName(), equalTo( originalLog.getName() ) ); assertThat( choppedLog, sameInstance( originalLog ) ); }
@Test public void originalFileIsReplacedWithChoppedFile() throws IOException { File originalLog = cloneFile( templateLog ); File choppedLog = FileBeheader.chop( originalLog, originalLog.length() ); assertThat( choppedLog.getName(), equalTo( originalLog.getName() ) ); assertThat( choppedLog, sameInstance( originalLog ) ); }
@Test public void keepsOriginalSizeWhenTailIsLargerThanOriginalSize() throws IOException { File originalLog = cloneFile( templateLog ); long originalLength = originalLog.length(); long tailBiggerThanOriginalSize = originalLength + 10; File choppedLog = FileBeheader.chop( originalLog, tailBiggerThanOriginalSize ); assertThat( choppedLog.length(), equalTo( originalLength ) ); }