Tirthankar
Tirthankar

Reputation: 615

How to read a file containg just 1 line or 1 word in Java

I have a file, I know that file will always contain only one word. So what should be the most efficient way to read this file ?

Do i have to create input stream reader for small files also OR Is there any other options available?

Upvotes: 0

Views: 200

Answers (5)

Vallabh Patade
Vallabh Patade

Reputation: 5110

Use BufferedReader and FileReader classes. Only two lines of code will suffice to read one word/one line file.

            BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
    System.out.println(br.readLine());

Here is a small program to do so. Empty file will cause to print 'null' as output.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

 public class SmallFileReader
       public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
            System.out.println(br.readLine());  
   }
 }

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

- Use InputStream and Scanner for reading the file.

Eg:

public class Pass {

    public static void main(String[] args){

        File f = new File("E:\\karo.txt");
        Scanner scan;
        try {
            scan = new Scanner(f);


        while(scan.hasNextLine()){

            System.out.println(scan.nextLine());
        }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

- Guava Library handles this beautifully and efficiently.

Upvotes: 0

SkyWalker
SkyWalker

Reputation: 14309

Efficient you mean performance-wise or code simplicity (lazy programmer)?

If it is the second, then nothing I know beats: String fileContent = org.apache.commons.io.FileUtils.readFileToString("/your/file/name.txt")

Upvotes: 0

Android Killer
Android Killer

Reputation: 18489

Use Scanner

File file = new File("filename");
Scanner sc = new Scanner(file);
System.out.println(sc.next()); //it will give you the first word

if you have int,float...as first word you can use corresponding function like nextInt(),nextFloat()...etc.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

Well something's got to convert bytes to characters.

Personally I'd suggest using Guava which will allow you to write something like this:

String text = Files.toString(new File("..."), Charsets.UTF_8);

Obviously Guava contains much more than just this. It wouldn't be worth it for this single method, but it's positive treasure trove of utility classes. Guava and Joda Time are two libraries I couldn't do without :)

Upvotes: 3

Related Questions