File handling in java

4 minute read

Read/Write file

// Using Scanner
  try {
    //Create file object
    File file = new File("test.txt");
    // Open file
    Scanner scan = new Scanner(file);
    while(scan.hasNextLine()){
      System.out.println(scan.nextLine());
    }
    //System.out.println(scan.useDelimiter("\\z").next());
  } catch (FileNotFoundException e) {
    // TODO: handle exception
  }

// Using BufferedReader
  try {
        // Create file object
        File file = new File(fname);
        // InputStream
        FileReader filereader = new FileReader(file);
        // BufferedReader
        BufferedReader bufReader = new BufferedReader(filereader);
        String line = "";
        while((line = bufReader.readLine()) != null){
          if (line.substring(0,1).equals("#"))
            continue;
          System.out.println(line);
        }
      }
      //.readLine() doesn't read carriage return("\n")
        bufReader.close();
      } catch (FileNotFoundException e) {
        // TODO: handle exception
      } catch(IOException e) {
        System.out.println(e);
      }

FileHandler

import java.io.*;
import java.nio.ByteBuffer;

public class FileHandler {

    private final static int MAX_DATA_SIZE = 999999;
    private String mCharset = C.CHARSET_TO;

    private long mFileSize = 0;
    private long mStartPos = 0;
    private String mFileName = null;
    private FileReader mFileReader = null;
    private FileWriter mFileWriter = null;

    private FileInputStream mFileInputStream = null;
    private FileOutputStream mFileOutputStream = null;

    public char[] mCharArr = new char[MAX_DATA_SIZE];
    public byte[] mByteArr = new byte[MAX_DATA_SIZE];
    /**
     * Creator
     * @param fname
     * @throws Exception
     */
    public FileHandler(String fname) throws Exception {
        mFileName = fname;
    }

    /**
     * Set Charset
     * @param cs
     */
    public void setCharset(String cs) {
        mCharset = cs;
    }

    /**
     * Close file resources
     * @throws Exception
     */
    public void close() {
        try {
            if (mFileReader != null) {
                mFileReader.close();
                mFileReader = null;
            }
            if (mFileWriter != null) {
                mFileWriter.close();
                mFileWriter = null;
            }
        } catch (Exception e) {
            LOG.error("Failed to close FileHandler : " + e.getMessage());
        }
    }

   /**
     * File size
     * @return
     */
    public long getSize() {
        // File Size
        File file = new File(mFileName);
        if (file.exists()) {
            mFileSize = file.length();
        } else {
            LOG.error(String.format("File does no exist[%s]", mFileName));
            return -1;
        }
        return mFileSize;
    }

    /**
     * Read file
     * @param offset
     * @param length
     * @return
     * @throws IOException
     */
    public String readFile(int offset, int length) throws IOException
    {
        return readFile((long)offset, (long)length);
    }

   /**
     * Read file with FileInputStream
     * @param offset
     * @param length
     * @throws IOException
     */
    public byte[] readFileByte(int offset, int length)
    {
        int idx = 0;
        int recvBytes = 0;
        int totRecvBytes = 0;

        try {
            if (mFileInputStream == null) {
                mFileInputStream = new FileInputStream(mFileName);

                // File Size
                File file = new File(mFileName);
                if (file.exists())
                    mFileSize = file.length();
            }

            // Move position
            long skip = mFileInputStream.skip(offset);
            LOG.debug(String.format("===> readFileByte() [LINE:%d][skip:%d][available:%d]", UTILS.getLineNumber(), skip, mFileInputStream.available() ));

            while (totRecvBytes < length) {
                LOG.debug(String.format("===> readFileByte() offset:(%d) length:(%d) filesize:(%d) total/recv: [%d][%d]", offset, length, mFileSize, totRecvBytes, recvBytes));
                recvBytes = mFileInputStream.read(mByteArr, totRecvBytes, length-totRecvBytes);
//                LOG.info(String.format("recvData() read[%d]", recvBytes));
                if(recvBytes < 0)
                {
                    LOG.error(String.format("[LINE:%d] readFileByte() ERROR", UTILS.getLineNumber(), recvBytes));
                    throw new IOException("Disconnected..");
                }
                totRecvBytes+=recvBytes;
            }

            ByteBuffer byteBuffer = ByteBuffer.allocate(totRecvBytes);
            byteBuffer.put(mByteArr, 0 , totRecvBytes);

            LOG.debug(String.format("===> readFileByte() : idx:[%d], length:[%d], totRecvBytes:[%d], filesize:[%d]", idx, length, totRecvBytes, mFileSize));
            mFileInputStream.close();
            mFileInputStream = null; // If it is not closed, it'll skip the position and available value would be 0.
            return byteBuffer.array();
        }
        catch (IOException e) {
            LOG.error(String.format("readFile() IOException. offset:[%d], length[%d], filesize:[%], Msg:[%s]",
                    offset, length, mFileSize, e.getMessage()));
        }
        return null;
    }

   /**
     * Read file with FileReader
     * @param offset
     * @param length
     * @return
     */
    public String readFile(long offset, long length)
    {
        try {
            if (mFileReader == null) {
                mFileReader = new FileReader(mFileName);

                // File Size
                File file = new File(mFileName);
                if (file.exists())
                    mFileSize = file.length();

                // Move position
                mFileReader.skip(offset);
            }

            // Read file
            int singleCh = 0;
            int idx = 0;

            while((singleCh = mFileReader.read()) != -1 && idx < length) {
                mCharArr[idx] = (char)singleCh;
                byte[] b = new byte[(int)singleCh];
                idx++;
            }
            //return new String(String.valueOf(mCharArr).getBytes(C.CHARSET_TO));
            return new String(mByteArr, 0, (int)length, C.CHARSET_TO);
        }
        catch (IOException e) {
            LOG.error(String.format("readFile() IOException. sendBytes[%d] totalLength[%d]. Msg[%s]", offset, length, e.getMessage()));
            return "";
        }
    }

    /**
     * Write to file
     * @param datstr
     * @param offset
     * @param length
     * @throws Exception
     */
    public void writeFile(String datstr, long offset, long length) throws Exception {
        writeFile(datstr, (int)offset, (int)length);
    }

   /**
     * Write to file with FileWriteStream
     * @param datstr
     * @param offset
     * @param length
     * @return
     * @throws IOException
     */
    public void writeFile9(String datstr, int offset, int length) throws Exception {

        if (mFileOutputStream == null) {
            mFileOutputStream = new FileOutputStream(mFileName);
        }
        mFileOutputStream.write(datstr.getBytes(), offset, length);
        mFileOutputStream.flush();
    }

    /**
     * Write to file with FileWriter
     * @param datstr
     * @param offset
     * @param length
     * @throws Exception
     */
    public void writeFile(String datstr, int offset, int length) throws Exception {
            File file = new File(mFileName);
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.skipBytes(offset);
            raf.writeBytes(datstr);
            raf.close();
    }

    /**
     * Write to file with FileWriter
     * @param datstr
     * @param offset
     * @param length
     * @throws Exception
     */
    public void writeFile2(String datstr, int offset, int length) throws Exception {
        if (mFileWriter == null) {
            mFileWriter = new FileWriter(mFileName);
        }
        mFileWriter.append(datstr, offset, length);
        mFileWriter.flush();
    }

    /**
     * Write to file
     * @param arr
     * @param offset
     * @param length
     * @throws Exception
     */
    public void writeFileByte(byte[] arr, long offset, long length) throws Exception {
        writeFileByte(arr, (int)offset, (int)length);
    }

    /**
     * Write to file with FileWriter
     * @param arr
     * @param offset
     * @param length
     * @throws Exception
     */
    public void writeFileByte(byte[] arr, int offset, int length) throws Exception {
        File file = new File(mFileName);
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.skipBytes(offset);
        raf.write(arr, 0, length);
        raf.close();
    }
}

Tags:

Categories:

Updated:

Leave a comment