Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.zybnet;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.LinkedList;
- import java.util.List;
- import junit.framework.TestCase;
- public class RemoveLine extends TestCase {
- /**
- * @param args args[0] is the filename, args[1] is the line number
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // Use a random access file
- RandomAccessFile file = new RandomAccessFile(args[0], "rw");
- int counter = 0, target = Integer.parseInt(args[1]);
- long offset = 0, length = 0;
- // Find offset and length of target line
- while (file.readLine() != null) {
- counter++;
- if (counter == target)
- break;
- offset = file.getFilePointer();
- }
- length = file.getFilePointer() - offset;
- if (target > counter) {
- file.close();
- throw new IOException("No such line!");
- }
- byte[] buffer = new byte[4096];
- // the file pointer is set at the end of the target line
- int read = -1;
- while ((read = file.read(buffer)) > -1){
- // go back
- file.seek(file.getFilePointer() - read - length);
- file.write(buffer, 0, read);
- // go ahead by length
- file.seek(file.getFilePointer() + length);
- }
- file.setLength(file.length() - length);
- file.close();
- }
- public static void testMain() throws IOException {
- String[] lines = {"Lorem", "Ipsum", "Dolor", "Sit", "Amen"};
- String tmpFile = "/tmp/a";
- int index = 1;
- BufferedWriter out = new BufferedWriter(new FileWriter(tmpFile));
- for (String line : lines) {
- out.write(line);
- out.write("\n");
- }
- out.close();
- main(new String[] {tmpFile, Integer.toString(index)});
- List<String> read = new ArrayList<String>(lines.length);
- String line = null;
- BufferedReader in = new BufferedReader(new FileReader(tmpFile));
- while ((line = in.readLine()) != null) {
- read.add(line);
- System.err.println(line);
- }
- in.close();
- List<String> src = new LinkedList<String>(Arrays.asList(lines)) ;
- src.remove(index - 1);
- assertEquals(src, read);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement