Showing posts with label readfile. Show all posts
Showing posts with label readfile. Show all posts

Wednesday, March 25, 2015

How to open file and go to the specific line or text string in Linux

P
This tutorial could resolve a problem that you want to edit a text file with the line number goes up to a hundred. Now you don't have to scroll down and wait until you're at the line need to be changed.
Please note that, this tutorial I am going to show you just works with vi/vim command, so your PC must be installed either of them.

About usage, vi and vim has the same way to use. Now I will show you how to do this

vi +SearchString fileName

Or

vi +LineNumber fileName

Others ways

vi +/SearchString fileName
vi +/LineNumber fileName
vim +/LineNumber fileName

Sample

In case you want to open Hello.java at line 90
vi +90 Hello.java

In case you want to open Hello.java at function say()
vim +/"say()" Hello.java

References

Thursday, March 5, 2015

Read file to byte array in Java

P
There are many ways to read a file to byte array in Java, now in this post, I just give you to ways.
1/ Use java.io

public static byte[] read(String path) throws IOException {
     File file = new File(path);
     ByteArrayOutputStream ous = null;
     InputStream ios = null;
     try {
         byte[] buffer = new byte[4096];
         ous = new ByteArrayOutputStream();
         ios = new FileInputStream(file);
         int read = 0;
         while ( (read = ios.read(buffer)) != -1 ) {
             ous.write(buffer, 0, read);
         }
     } finally { 
         try {
              if ( ous != null ) 
                  ous.close();
         } catch ( IOException e) {
         }

         try {
              if ( ios != null ) 
                   ios.close();
         } catch ( IOException e) {
         }
     }
     return ous.toByteArray();
 }

2/ Use org.apache.commons.io.IOUtils

public static byte[] read(String path) throws IOException {
   InputStream in = new FileInputStream(path);
   return IOUtils.toByteArray(in);
  }

You can download apache library from here.