Posted in Uncategorized

[Java Core] File handling in Java

java_logo_100

In Java, we often handle a file. Now, I want to introduce some code for handling file basically.

  • Create a folder
public void createFolder(String newFolderPath) {
    new File(newFolderPath).mkdir();
}
  • Create a folder and its subfolder
/**
* @param path such as "C:\\Directory2\\Sub2\\Sub-Sub2"
*/
public void createFolderAndItsSubFolders(String path) {
   new File(path).mkdirs();
}
  • Check a folder existed or not
/**
* @param path such as "C:\\Directory1"
*/
public boolean isExistedFolder(String folder) {
   File file = new File(folder);
   return file.exists();
}
  • Create new file
public void createNewFile(String filePath) {
    try {
      File file = new File(filePath);
      if (file.createNewFile()) {
        System.out.println("File is created!");
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
 }
  • Delete a file
public void deleteFile(String filePath) {
    try {
      File file = new File(filePath);
      if (file.delete()) {
        System.out.println(file.getName() + " is deleted!");
      } else {
        System.out.println("Delete operation is failed.");
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("IOException: " + e.getMessage());
    }
  }
  • Open a file by default app in PC such as open HTML file on Chrome
public void openFileOnDefaultApp(String filePath) {
    File htmlFile = new File(filePath);
    try {
      Desktop.getDesktop().browse(htmlFile.toURI());
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("IOException: " + e.getMessage());
    }
 }

 

You also can find above source at this class file

Like and share this topic if it is helpful for you 🙂

Advertisements
Posted in JavaScript, Useful Script

Javascript useful script [Part 1]

javascript

In this topic, I will provide some useful scripts in Javascript, they can help us a lot for coding

  1. Array
  • .filter()

Create a new array base on an existed array with filter conditions.

const studentAge= [17,16,18,19,21,15]
const ableToDrink = studentsAge.filter( age => age > 18 );
// Result: ableToDrink= [19,21]
  • .map()

Create a new array by copying and editing data of an existed array

// Example: create new array from numbers array and add '&' for each element
const numbers = [2, 3, 4, 5];
const dollars = numbers.map( number => '$' + number);
// Result: dollars = ['$2', '$3', '$4', '$5']
  • .forEach()

Do a certain action on each element in an array

const emotions = ['happy', 'sad', 'angry'];
emotions.forEach( emotion => console.log(emotion) );
// Result will disply one by one
// 'happy'
// 'sad'
// 'angry'
  • .some()

Check if any element in array satisfy a certain condition. If yes, return true, otherwise, return false.

 
const userPrivileges = ['user', 'user', 'user', 'admin'];
const containsAdmin = userPrivileges.some( element => element === 'admin');
// Result: containsAdmin = true, because array has element that contain 'admin'
  • .every()

Like ‘.some()’ function but check all of elements with condition.

const ratings = [3, 5, 4, 3, 5];
const goodOverallRating = ratings.every( rating => rating >= 3 );
// Result: goodOverallRating = true, because every element in array >= 3

 

2) Others

 

Like & Share if this topic is helpful for you 🙂

Posted in Java

[Java Core] How to read/write file in Java ?

java_logo_100

In Java, we often face the requirement to read content from a file or write content to file. In Java, we have many ways to do that :).

A) How to READ file?

  • Using BufferedReader is the simplest and most common-used method. It helps us read file line by line:

public class ReadWriteFileHandler {

public void readFileByBufferedReader(String fileName) {
 BufferedReader br = null;
 FileReader fr = null;
 try {
   fr = new FileReader(fileName);
   br = new BufferedReader(fr);
   String currentLine = "";
   while ((currentLine = br.readLine()) != null) {
// Read line by line
      System.out.println(currentLine);
   }
 } catch (IOException e) {
   e.printStackTrace();
 } finally {
   try {
     if (br != null)
        br.close();
     if (fr != null)
        fr.close();
    } catch (IOException ex) {
     ex.printStackTrace();
    }
   }
 }

}

 

 

B) How to WRITE file?

Using BufferedWriter to write content to a file, create the file if doesn’t exist, the existing content will be overridden.

The BufferedWriter is a character stream class to handle the character data. Unlike byte stream (convert data into bytes), you can just write the strings, arrays or character data directly to a file.

Please find an example below:


public void writeFile(String fileName, String content) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("Write Done !");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();

}

}
}

 

Basically, you can refer above code from ReadWriteFileHandler.java

Hope this topic helpful for you :), please share if you like it 🙂