2

I have to read a text file in Java, for that I am using below code:

Scanner scanner = new Scanner(new InputStreamReader(
    ClassLoader.getSystemResourceAsStream("mock_test_data/MyFile.txt")));

scanner.useDelimiter("\\Z");
String content = scanner.next();
scanner.close();

As far as I know String has MAX_LENGTH 2^31-1

But this code is reading only first 1024 characters from input file(MyFile.txt).

I am not able to find the reason.

rtruszk
  • 3,902
  • 13
  • 36
  • 53
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47

3 Answers3

2

Thanks for your answers:

Finally I have found solution for this-

 String path = new File("src/mock_test_data/MyFile.txt").getAbsolutePath();
 File file = new File(path);
 FileInputStream fis = new FileInputStream(file);
 byte[] data = new byte[(int) file.length()];
 fis.read(data);
 fis.close();
 content = new String(data, "UTF-8");

As i have to read a very long file at once.

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
2

I've read some of the comments and therefore I think it's necessary to point out that this answer does not care about good or bad practice. This is a stupid nice-to-know scanner trick for lazy people who need a quick solution.

final String res = "mock_test_data/MyFile.txt"; 

String content = new Scanner(ClassLoader.getSystemResourceAsStream(res))
     .useDelimiter("\\A").next();

Stolen from here...

Doe Johnson
  • 1,374
  • 13
  • 34
  • Could you please provide some better solution Which will take card about performance as well. – Gaurav Jeswani Jul 02 '15 at 17:42
  • Your question does not mention any performance requirements at all. You wanted a solution which reads a file/stream completely... Here you go. I won't make any assumptions about performance as there are many factors which go way beyond some lines to read in a file. Besides, performance alone means nothing. There's also readability for instance. – Doe Johnson Jul 02 '15 at 20:35
0

Example of using BufferedReader, works great for big files:

public String getFileStream(final String inputFile) {
        String result = "";
        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader(inputFile)));
            while (s.hasNext()) {
                result = result + s.nextLine();
            }
        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
        return result;
}

FileInputStream is used for smaller files.

Using readAllBytes and encoding them solves problem as well.

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

You can take a look at this question. It is very good.

Community
  • 1
  • 1
Aleksandar
  • 1,163
  • 22
  • 41