-2

I need to read text file to String. I do :

BufferedReader br = null;
        try {

            br = new BufferedReader(new FileReader(filePath));
            String line = br.readLine();
            String everything = line;

            while (line != null) {
                line = br.readLine();
                everything += line + "\n";
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

But I dont like to read line by line. It should be possible to read whole file to string at one function call. I'm right? By the way, I must use java 1.4.

Rustam
  • 6,307
  • 1
  • 21
  • 25
vico
  • 13,725
  • 30
  • 108
  • 237

2 Answers2

0

If you are allowed to use an external library, you could have a look on Apache Commons FileUtils

Besides, you definitely should not use such an old java version.

u6f6o
  • 1,728
  • 2
  • 23
  • 47
0

you can read the whole file data as byte array.

File file = new File(yourFileName);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String strData=new String(data, "UTF-8"); // converting byte array to string
System.out.println(strData);
Pshemo
  • 113,402
  • 22
  • 170
  • 242
Rustam
  • 6,307
  • 1
  • 21
  • 25