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;
}
Files.list()
expects a path pointing to the directory as a parameter, and it'll give you a stream ofPath
objects (if any) contained in this directory. In case if the given path will be a file, you will get aNotDirectoryException
exception. You can't access the contents of a file withFiles.list()
, it's simply meant for another purpose.In order to read from the text file you can use either
Files.lines()
orFiles.readAllLines()
.Contrary to
Files.readAllLines()
which dumps all file content into memory, the stream produced byFiles.lines()
will be populated lazily. Hence, in a general caseFiles.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 be an array of strings. It will be both 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 (whichreadAllLines()
returns) and then creating a string array based on this list.With
Files.lines()
it could be implemented like that:There are several important issues in your code:
finally
block or by using try with resources, as shown above (which preferred and more concise way).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.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:
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.