Monday, May 14, 2012

Read text file using Java code

Example to read text from file:

package javafile;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class ReadStringFromFile {
    
    public static void main(String[] args) {
        
        File file = new File("C:/test/test.txt");
        
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        
        try {

            bufferedReader = new BufferedReader(new FileReader(file));
            
            String text;
            while ((text = bufferedReader.readLine()) != null) {
                stringBuffer.append(text);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReadStringFromFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReadStringFromFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                Logger.getLogger(ReadStringFromFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
                
        System.out.println(stringBuffer);
                
    }
    
}


Next:
- Read text file with JavaFX FileChooser


No comments:

Post a Comment