31 janeiro 2018

How to use Queue in Java


public class QueueDemo {

    public static void main(String args[]) {
        Queue months = new LinkedList<>();
        // Example 1 - Adding objects into Queue
        System.out.println("Queue : " + months);
        months.add("JAN");
        months.add("FEB");
        months.add("MAR");
        months.add("APR");
        months.add("MAY");
        months.add("JUN");
        months.add("JUL");
        months.add("AUG");
        months.add("SEP");
        months.add("OCT");
        months.add("NOV");
        months.add("DEC");
        System.out.println("Queue after initialization : " + months);

        // Example 2 - Checking if an Object is in Queue or not
        boolean hasMay = months.contains("MAY");
        System.out.println("Does Queue has MAY in it? " + hasMay);

        // Example 3 - Retrieving value from head of Queue
        String head = months.peek();
        System.out.println("Head of the Queue contains : " + head);

        // Example 4 - Removing objects from head of the Queue
        String oldHead = months.poll();
        String newHead = months.peek();
        System.out.println("old head : " + oldHead);
        System.out.println("new head : " + newHead);

        // Example 5 - Another way to remove head objects from Queue
        months.remove();
        System.out.println("now head of Queue is: " + months.peek());
    }
}


Source: java67.com

25 janeiro 2018

FileInputStream / FileOutputStream - new ways to code

From Java7 that we must use FileInputStream and FileOuputStream as described below

public void writeToFile(String fileName, byte[] content) throws IOException {
    try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) {
        os.write(content);
    }
}
public byte[] readFromFile(String fileName) throws IOException {
    byte[] buf = new byte[8192];
    try (InputStream is = Files.newInputStream(Paths.get(fileName))) {
        int len = is.read(buf);
        if (len < buf.length) {
            return Arrays.copyOf(buf, len);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream(16384);
        while (len != -1) {
            os.write(buf, 0, len);
            len = is.read(buf);
        }
        return os.toByteArray();
    }
}

Source: dzone.com

10 things to remember while reading, writing from/to a file in Java

10 essential things Java developer should know about File handling in Java programming language.  

1) The same java.io.File class is used to represent both file and directory in Java. You can use the isDirectory() and isFile() method from the java.io.File class to check if you are actually working with a file or directory.  See this article to learn more about File and Directory in Java.

2) In Java, InputStream is used for reading data and OutputStream is used for writing data. In the context of a file, FileInputStream is used to read data from a file and FileOutputStream is used to write data into the file. I know, it's easy to remember that one you know but I have seen many Java programmers struggling with InputStream and OuputStream and their meaning.

3) Java provides different classes for different needs in java.io package, for example, Stream classes e.g. InputStream and OutputStream are used to read and write binary data while Reader and Writer e.g. BufferedReader and BufferedWriter are used to writing character or text data.

4) It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it, while in the output stream, the close() method calls flush() before releasing the resources which force any buffered bytes to be written to the stream. See Complete Java 9 Masterclass to learn more about how to close Stream in right way.

5) If we try to read from a file that doesn’t exist, a FileNotFoundException will be thrown but If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown

6) FileReader and FileWriter classes are used to read/write data from a text file in Java. Even though you can use FileInputStream and FileOutputStreamFileReader and FileWriter are more efficient and handles character encoding issues for you. You can see the difference between FileReader and FileInputStream to learn more about that.

7) If you are dealing with a shared file then make sure you lock the file before writing into it. You can use the FileLock interface for locking the portion of the file. You can get the associated lock for a file by calling the FileChannel.getLock() method. See here for an example of locking a file in Java before writing into it.

8) Make sure you know the right way to close the stream in Java because calling the close itself can throw IOException. See my post about how to properly close input and output stream in Java to learn more.

9) The java.io and java.nio package provides several classes to write different kinds of data on the different situation.  For example, you can use
  •  PrintWriter to write formatted text;
  •  FileOutputStream to write binary data; 
  •  FileWrite to writer text data, 
  •  DataOutputStream to write primitive data types; 
  •  RandomAccessFile to write to a specific position, and 
  •  FileChannel to write faster in bigger files.

10) Use the JDK 7 new file API as much as possible, particularly for writing new code. Spend some time know and understand the new File API introduced in JDK 7, at least the java.nio.file.Files class, which allows you to create, read, write, copymove, and delete files and directories in Java.

Source: www.java67.com