Reputation: 4592
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.
Upvotes: 2
Views: 1370
Reputation: 4592
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.
Upvotes: 2
Reputation: 1414
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...
Upvotes: 2
Reputation: 1173
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.
Upvotes: 0