August 14, 2022

How to assign file content into a variable in Java

Most people will read the file content and assign to StringBuffer or String line by line. Here’s another trick that may interest you – how to assign whole file content into a variable with one Java’s statement, try it 🙂. In this example, you will use DataInputStreamto convert all the content into bytes, and create a String variable with the converted bytes.

How to assign file content into a variable in Java Read More

How to read file in Java – FileInputStream

In Java, we use FileInputStream to read bytes from a file, such as an image file or binary file. The FileInputStream.read() reads a byte at a time, and it will return a -1 if it reached the end of the file. The FileInputStream.available() to check the remaining bytes that can be read. The FileInputStream.read(byte b[]) to read predefined bytes into a byte array; it will significantly increase the read performance. The common practice uses BufferedInputStream to wrap the FileInputStream to provide a buffer cache to increase the read performance. It’s also common to use InputStreamReader to convert FileInputStream to BufferedReader, and read it line by line.

How to read file in Java – FileInputStream Read More

How to set the file permission in Java

In Java, file permissions are very OS specific: *nix , NTFS (windows) and FAT/FAT32, all have different kind of file permissions. Java comes with some generic file permission to deal with it: Executable, Readable, Writable. In *nix system, you may need to configure more specifies about file permission, e.g set a 777 permission for a file or directory, however, Java IO classes do not have ready method for it, but you can use the following dirty workaround : Runtime.getRuntime().exec(“chmod 777 file”);

How to set the file permission in Java Read More