tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Articles > Java > Basics > How to convert file content to String

How to convert file content to String 

The following example shows converting file content to java string. This works fine when converting text files to String. But binary files such as Word DOCs, PDFs and images which cannot be represented as string may loose its actual value when encoded as a string.

File Name  :  
com/bethecoder/articles/basics/file2str/File2StringTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.articles.basics.file2str;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class File2StringTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    //Get contents of file as string
    String str = fileToString("C:/ABC.txt");
    System.out.println(str);
  }

  public static String fileToString(String filePath) {
    return fileToString(new File(filePath));
  }
  
  public static String fileToString(File file) {

    byte [] fileBytes = new byte[0];
    
      try {
          byte [] buffer = new byte[4096];
          ByteArrayOutputStream outs = new ByteArrayOutputStream();
          InputStream ins = new FileInputStream(file);
          
          int read = 0;
          while ((read = ins.read(buffer)) != -) {
            outs.write(buffer, 0, read);
          }
          
          ins.close();
          outs.close();
          fileBytes = outs.toByteArray();
          
      catch (Exception e) { 
        e.printStackTrace();
      }
      
      return new String(fileBytes);
  }
}
   

It gives the following output,
ABC ABC ABC
ABC ABC ABC
ABC ABC ABC



 
  


  
bl  br