Last active
September 19, 2024 07:13
-
-
Save chanakaDe/66390cf8be65b86cf173998633b707cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. This class is identified as a Thread safe class. But the thread safety is being mis-used here. | |
setFile() and getFile() methods are synchronized. The getContent(), getContentWithoutUnicode() and saveContent() | |
methods are not synchronized. So the concurrent access by multiple threads could lead to invoke errors. | |
2. Exception handling has been totally ignored here. Here in this code we are using IO (Input / Output). Its important to have exception handling. | |
public synchronized String getContent() throws IOException { | |
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { | |
StringBuilder output = new StringBuilder(); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
output.append(line).append(System.lineSeparator()); | |
} | |
return output.toString(); | |
} | |
} | |
3.. Misuse of String Concatenation. Its very important to use StringBuilder in cases like this. This code generates new String objects | |
in the way how it is now. A very primitive way of memory management. | |
StringBuilder output = new StringBuilder(); | |
while ((data = i.read()) > 0) { | |
output.append((char) data); | |
} | |
return output.toString(); | |
4..FileInputStream & FileOutputStream are not closed. This can be a significant resource leak. Better to wrap them in a Try,Catch in | |
order to automatically close streams after they are used. | |
5. Handle File encoding. This class cannot handle multi-byte characters. It is not adviced to use raw byte streams without | |
Character Encoding Handling. | |
6. Need to Explicitly specify UTF-8 character encoding to avoid issues with different encodings. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment