Read a File to a String
You don’t need to create a method for this. The recommended way to read an entire file to a String
is the next:
String dados = new String(Files.readAllBytes(file.toPath()));
Preferably, specify a encoding to avoid problems with special characters:
String dados = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
Problems with some implementations
Concatenating Strings
One of the answers offers:
public static String addItemCreative(File f) {
String line, lines = "";
try {
BufferedReader br = new BufferedReader(new FileReader(f));
while ((line = br.readLine()) != null) {
lines += line;
}
} catch (Exception e) {
e.getMessage();
}
return lines;
}
This is not good because each concatenation of two Strings generates a third and memory is consumed exponentially. If the file is large, it will force the Garbage Collector to run several times, pausing the execution of the program and leading to very bad performance.
The right thing to do is to use StringBuilder
in local implementations, which is a class that allows concatenating Strings without the need to synchronize the object. The @Cantoni response provides an example of how to do this.
Line breaks
If the file has line breaks, you are ignoring them by joining in the String. By calling the method readLine
Java does not include breaks.
If you want the contents of the String to match the contents of the file, you must concatenate the breaks manually.
Calling readLine
more than once
In the implementation of the question, the method readLine
is called twice. If the file contains a single line, the second call will return null
.
If the file has more lines, the result will be a String with the odd lines of the file.
Handling of exceptions
The exception that must be captured is IOException
. Do not capture more generic exceptions unnecessarily. You may end up covering up mistakes.
Also, call the method getMessage
does nothing. At least you should print the error log to understand what is happening. For example:
} catch(IOException e) {
e.printStackTrace();
}
Or capture the mistake and do something with it
} catch(IOException e) {
String erro = e.getMessage();
mostraErro(erro);
}
Missing close the file
In Java it is easy to forget that not every resource allocated is automatically released.
When opening a file for reading or writing, remember to close the file later.
This can be done through the method close
of one of the Reader
used or automatically through try-with-resources
of Java 6. Example:
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
...
}
In the above code, the method close
of BufferedReader
will be automatically invoked at the end of the block try
.
Good practice in general
Use variables in the smallest possible scope. Instead of declaring the variable line
at the beginning of the method, it can be inside the block try
and in the catch
you return null directly. Reusing variables can be confusing.
A possible implementation bringing together everything I described above would be:
String quebra = System.getProperty("line.separator");
public String addItemCreative(File f) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null){
sb.append(line);
sb.append(quebra);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Optional return
If you want to go further and semantically reinforce that the method has an optional return, for example in case the file does not exist or is empty, you can use the new Java 8 interfaces as Optional
.
These interfaces avoid the need to use the null
to specify no value. This avoids many NullPointerException
s for lack of attention, since it forces the client code to verify if there is a value returned by the method.
Example:
String quebra = System.getProperty("line.separator");
public Optional<String> addItemCreative(File f) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null){
sb.append(line);
sb.append(quebra);
}
return sb.length() > 0 ? Optional.of(sb.toString()) : Optional.empty();
} catch (IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
Now it is easy who calls the method to know that it may not return some value.
Assuming you wanted to print the content. The method could be used like this:
Optional<String> conteudo = addItemCreative(arquivo);
if (conteudo.isPresent()) {
imprimir(conteudo.get());
} else {
imprimir("[arquivo vazio]");
}
Still, if you prefer a more functional format:
imprimir(addItemCreative(arquivo).orElse("[arquivo vazio]"));
Puts a
sysout
within thewhile
and see if it’s displayed.– DiegoAugusto
Can you put the contents of the file in the question? Just click on [Edit].
– Jéf Bueno