Java File Append Text appendToFile(String filename, String content, int line)

Here you can find the source of appendToFile(String filename, String content, int line)

Description

append To File

License

Apache License

Declaration

public static void appendToFile(String filename, String content, int line) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.io.RandomAccessFile;

public class Main {

    public static void appendToFile(String filename, String content, int line) {
        try {//w  w  w.j av  a 2  s  .  co m
            RandomAccessFile randomFile = new RandomAccessFile(filename, "rw");
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);

            long end = randomFile.getFilePointer();
            int j = 0;
            long a = 0;
            while ((end >= 0) && (j <= 2)) {
                end--;
                randomFile.seek(end);
                byte n = randomFile.readByte();
                if (n == '\n') {
                    a = randomFile.getFilePointer();
                    j++;
                    if (j == line) {
                        break;
                    }
                }
            }
            randomFile.seek(a);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related

  1. appendToFile(String content, File file, String encoding)
  2. appendToFile(String content, String filename)
  3. appendToFile(String contents, String filename)
  4. appendToFile(String file, String line)
  5. appendToFile(String fileName, String content)
  6. appendToFile(String filename, String str)
  7. appendToFile(String filename, String text)
  8. appendToFile(String fileName, String text)
  9. appendToFile(String filename, String text)