Simple file operations..

Module for create files, append data to files, create folders, check if exists file or folders etc etc..

/* =====================================================================
     Project : Simple operations with text/binary files.
      Author : Erkosone
     Created : 17 Jan 2017
                                     Processing Version tested : 3.0.1
======================================================================== */
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
//----------------------------------------------------------------
void fwrite(String filename, byte[] data, boolean append){
  Path file = Paths.get(filename);
  OutputStream output = null;
    try
    {
      if(append){
        output = new BufferedOutputStream(Files.newOutputStream(file, APPEND));
      }
      else{
        File f = new File(filename);
        f.delete();
        output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
      }
      output.write(data);
      output.flush();
      output.close();
    }
    catch(Exception e)
    {
        System.out.println("Message: " + e);
    }
}
//----------------------------------------------------------------
void fwriteLine(String fileName, String newData, boolean appendData){
  BufferedWriter bw = null;
  try {  
    FileWriter fw = new FileWriter(fileName, appendData);
    bw = new BufferedWriter(fw);
    bw.write(newData + System.getProperty("line.separator"));
  } catch (IOException e) {
  } finally {
    if (bw != null){
      try { 
        bw.close(); 
      } catch (IOException e) {}  
    }
  }
}
//----------------------------------------------------------------
boolean fileExists(String filename) {
  File file=new File(filename);
  boolean exists = file.exists();
  if (exists) {
    return true;
  }
  else {
    return false;
  }
}
//----------------------------------------------------------------
void createFile(String filename){
  BufferedWriter bw = null;
  try {  
    FileWriter fw = new FileWriter(filename, true);
    bw = new BufferedWriter(fw);
    bw.write("");
  } catch (IOException e) {
  } finally {
    if (bw != null){
      try { 
        bw.close(); 
      } catch (IOException e) {}  
    }
  }
}
//----------------------------------------------------------------
void copyFile(String sourceFile, String destFile){
  byte[] source = loadBytes(sourceFile);
  saveBytes(destFile, source);
}
//----------------------------------------------------------------
boolean mkDir(String folderName){
  File dir = new File(folderName);
  dir.mkdir();
  return fileExists(folderName);
}

Comments

Sign In or Register to comment.