I have a txt file with strings.
I want to get a String
array containing all lines from the file via Files.list(Paths.get("path"))
method.
I tried to use toArray()
but it returns an array of paths to files in "path" directory
How can I get it using Files.list(Paths.get("path"))
(it's mandatory)?
I have something like this:
public Object[] returnStrings(){
Object[] strings;
try {
strings = Files.list(Paths.get(path)).toArray();
}catch (IOException ex){
return null;
}
return strings;
}
CodePudding user response:
Files.list()
expects a path pointing to the directory as a parameter, and it'll give you a stream of Path
objects (if any) contained in this directory. You can't obtain the contents of a file with Files.list()
.
In order to read from the text file you can use either Files.lines()
or Files.readAllLines()
.
Contrary to Files.readAllLines()
which dumps all file content into memory, the stream produced by Files.lines()
will be populated lazily. Hence, in a general case Files.lines()
a preferred way to read from a file, especially when you're unaware of it's size.
For this task, even though all file's content has to be allocated in the memory (i.e. in this case the mentioned above upper-hand of a stream's laziness isn't important), Files.lines()
is a better choice because the expected result needs to an array of strings. It will be more performant and more space-efficient to generate an array as a result of execution of the stream pipeline, rather than reading the file into a list (which readAllLines()
returns) and then creating a string array based on this list.
With Files.lines()
it could be implemented like that:
public static String[] readFromFile(Path path) {
String[] result;
try(Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
result = stream.toArray(String[]::new);
} catch (IOException e) {
result = new String[0];
}
return result;
}
There are several important issues in your code:
- You are not closing the resource. Because stream is accessing the file, it has to be closed either explicitly inside the
finally
block or by using try with resources, as shown above (which preferred and more concise way). - It not a good idea to store
String
in the array ofObject
s because in order to do anything with these strings apart from printing them you will have to do an unsafe type casting. - It not very nice to return
null
in case when attempt to read from the file fails. Becausenull
can a cause a problem afterwards when it'll not be obvious where it came from.
And lastly, a few recommendations:
- Avoid placing the return statement inside the
try
andcatch
blocks, it reduces readability. List
is more convent and flexible container of data than array. In cases when you are not dealing with an existing code that expects an array, useList
instead.