Java : distinguish between read and close IOException? - java

Here is the simplified code :
public static void cat(File file) {
try (RandomAccessFile input = new RandomAccessFile(file, "r")){
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
return;
} catch(FileNotFoundException a){
;//do something to recover from this exception.
}catch(IOException b){
;//distinguish between close and readLine exception.
}
}
There are two situations when we may get IOEception :
Everything works out fine except closing the input.
readLine throws and IOException.
So how to distinguish between these two situations? Is there a good method to do this? Or should I just be reduced to do some string comparison of the exception message to distinguish between these two IOException?
Thanks! I just can't find a easy method to do this.

You can make a flag just before return
public static void cat(File file) {
boolean readAll = false;
try (RandomAccessFile input = new RandomAccessFile(file, "r")){
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
readAll = true;
return;
} catch(FileNotFoundException a){
;//do something to recover from this exception.
}catch(IOException b){
;//distinguish between close and readLine exception.
if (readAll) ...
}
}

Related

How to detect new line(or empty line) in a file?

I'm trying to write a program, which reads text from a file that is specified by the user. Now, this program should detect an empty line.
This is what I have unsuccessfully tried:
public static void editFile(String filePath) throws FileNotFoundException, IOException {
file = new File(filePath);
if(file.exists()) {
fileRead = new FileReader(file);
bufferedReader = new BufferedReader(fileRead);
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null) {
line = bufferedReader.readLine();
if(line == "") {
//line = null;
System.out.println("a");
}
System.out.println(line);
}
}
}
To be more clear:
If I'm passing in a text file with for example this text:
test1
test2
test3
test4
it should print 2 a's in the console because of the empty spaces, but it doesn't.
Thank you for your time, I am glad for any suggestion you may have.
This is because the comparison is wrong. You can't use == to compare two strings, you need to use the equals method:
if(line.equals(""))
Since you are checking for empty string, you can also write
if(line.isEmpty())
How do I compare strings in java?
BackSlash is entirely correct, and has answered your question. I'd like to add that your code has some errors:
You're not closing the Reader
You're not testing the first line for blank
You're processing the null value when reaching EOF
The following corrects these errors.
public static void editFile(String filePath) throws IOException
{
File file = new File(filePath);
if (file.exists())
{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try
{
String line;
while ((line = bufferedReader.readLine()) != null)
{
if (line.isEmpty())
{
//line = null;
System.out.println("a");
}
System.out.println(line);
}
} finally {
bufferedReader.close();
}
}
}
Output is:
test1
test2
a
test3
a
test4
Note: You're still printing the blank line in addition to the "a".
What you're doing wrong is that you're comparing the variable itself, not its value with a null string.
Generally there are built-in functions in the string class that return true & false for checking if it's == with something.
if(line.equals("")) { ... }
Or you can just use any alternative way.

Reading the content from an inputstream using scanner multiple times is not behaving as expected

I am using the following code to read content from an input stream.
#Test
public void testGetStreamContent(){
InputStream is = new ByteArrayInputStream("Hello World!!".getBytes());
System.out.println(getStreamContent(is));
System.out.println("Printed once");
System.out.println(getStreamContent(is));
}
public static String getStreamContent(InputStream is) {
Scanner s = null;
try {
s = new Scanner(is);
s.useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
} finally {
if (s != null){
s.close();
}
}
}
I'm expecting the output to contain Hello World!! twice, but it is not returning the text the second time. Following is the only output.
Hello World!!
Printed once
I have tried resetting the scanner by using s.reset(). But that is also not working.
Try this instead
ByteArrayInputStream is = new ByteArrayInputStream("Hello World!!".getBytes());
if(is.markSupported()){
is.mark("Hello World!!".length());
}
System.out.println(getStreamContent(is));
is.reset();
System.out.println("Printed once");
System.out.println(getStreamContent(is));
Things to note: I changed the variable type from InputStream to the instance type so I could call the methods specific to that type (mark, reset and markSupported ). That allows the stream to point back to the last marked position.
Calling a reset on inputstream is working for me.
public static String getStreamContent(InputStream is) throws IOException {
if(is == null)
return "";
is.reset();
Scanner s = null;
try {
s = new Scanner(is);
s.reset();
s.useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
} finally {
if (s != null){
s.close();
}
}
}

Still resource leak after closing BufferedReader

I'm still learning Java and I need some help understanding why this code is wrong:
BufferedReader infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
infile.close();
I really don't see the problem but Eclipse keeps telling there is a resource leak and that infile isn't closed.
(one more detail, this code stands in a try block but I left it away to keep it simple)
Eclipse is complaining because the reference may not be closed (for example, in an Exception); this is where you would use a finally block - perhaps like so
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
} catch (Exception e) {
e.printStackTrace(); // Log the exception.
} finally {
if (infile != null) {
infile.close(); // close the resource.
}
}
You should have a try/catch block.
Also you should use the following instead:
while ((line = reader.readLine()) != null) {
//do something with line;
}
I think Elliott Frisch is correct and pointed out the main reason the only thing I would add is You should close the stream (in a finally block) because to ensure that any output buffers are flushed in the case that output was otherwise successful. If the flush fails, the code should exit via an exception. Here is another example similar to what you are trying to solve and make sure you look at (Guideline 1-2: Release resources in all cases) http://www.oracle.com/technetwork/java/seccodeguide-139067.html
final OutputStream rawOut = new FileOutputStream(file);
try {
final BufferedOutputStream out =
new BufferedOutputStream(rawOut);
use(out);
out.flush();
} finally {
rawOut.close();
}

Reading lines with BufferedReader and checking for end of file

If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.

Bufferedwriter not saving *everything* to file

I am somewhat new to java and was hoping that someone could help me. I have looked everywhere, but cannot seem to finder a solution.
I'm trying to save the result of a method into a file using bufferedwriter. The bufferedwriter itself works as it is saving some other strings, but when it comes to this function is just displays 'null'. Is is because the result of this method returns more than one string? How do I resolve this?
My code is as following:
Bufferedwriter code:
public static boolean saveStringToFile (String fileName, String saveString)
{
boolean saved = false;
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new FileWriter(fileName));
try
{
bw.write(saveString);
saved = true;
}
finally
{
bw.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
return saved;
}
The function itself:
public static void getNetDetails()
{
try {
Process net = Runtime.getRuntime().exec("lsof -i -n -P");
BufferedReader netInput = new BufferedReader(
new InputStreamReader(net.getInputStream()));
while ((netDetails = netInput.readLine()) !=null)
{
System.out.println(netDetails);
System.out.println("\n");
}
}
catch(IOException e) {
System.out.println("exception happened - here are the details: ");
e.printStackTrace();
}
}
Saving function to file using bufferedwriter
public static void generateNetReport()
{
saveStringToFile("Net.txt","here is the thing.." + "\n" + netDetails );
}
can someone please help with how I can save netDetails onto a file without it just displaying null??
(Edited.)
This is the problem, in getNetDetails():
while ((netDetails = netInput.readLine()) !=null)
In other words, the method will always leave netDetails as null, unless there's an exception.
It would be better if getNetDetails() returned a string instead of setting a variable, and assuming it's meant to return the final line of the file, it should be something like:
String line = null;
String nextLine;
while ((nextLine = netInput.readLine()) != null) {
line = nextLine;
}
return line;
You should also close the InputStreamReader in a finally block, and almost certainly not swallow the exception.

Categories

Resources