Detect eof in java

how to check the end of a file in java

Everytime I execute this only the else part is executed. The if part never gets executed. Can somebody help me figuring out what is wrong in my code?

What are the contents of the file? Scanner#hasNextLine will be false when you reach the end of the file.

If it always goes to the else part, it means no line in the file contains the required string. Please show the contents of the file.

2 Answers 2

Use FileReader instead. Your code should look something like this:

String log = "/ws/priyapan-rcd/label" + "priyanka_label_test" + ".log"; File file = new File(log); try (BufferedReader br = new BufferedReader(new FileReader(file))) < String line; while ((line = br.readLine()) != null) < if (line.contains("script ran successfully")) < System.out.println("line found.go out of loop now"); break; >> > catch (Exception e)

(Why use this method? It should be slightly faster.)

EDIT: And like @Andrea spotted, be sure that you dont forgot a / between folder and file, when combining with a + .

That’s strange. Are you sure that your file is in /ws/priyapan-rcd/label/. ? That seems like an absolute path, and as I know, linux hasn’t a ‘base’ folder called ws .

the log file is /ws/priyapan-rcd/labelpriyanka_label_test.log and not /ws/priyapan-rcd/label/priyanka_label_test.log

@priyanka Please post the full location of the script and the file, so that I can take a look. Also please inform if your system is Windows or Linux.

@Fusseldieb..i am not sure if i can post the location here..but i think my script is working fine and all the o/p for the script is getting stored in the log file /ws/priyapan-rcd/label/» + «priyanka_label_test» + «.log»

I have executed above code and its working fine

import java.io.File; import java.util.Scanner; public class ReadFileScanner < public static void main(String s[]) < String log = "/tmp/ws/prakash-rcd/label" + "prakash_label_test" + ".log"; File file = new File(log); String line = null; try < Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) < line = scanner.nextLine(); System.out.println("come inside loop to check end of file: line: " + line); if (line.contains("script ran successfully")) < System.out.println("line found.go out of loop now"); break; >else < System.out.println("come inside loop to check logs.label update faild"); >> > catch(Exception e) < e.printStackTrace(); >> > 

It raises exception java.io.FileNotFoundException in case of file not found

The only suspect is, your log file may not have line «script ran successfully» that’s why code is not reaching if block statements

I executed the above code for file

come inside loop to check end of file: line: Start

come inside loop to check logs.label update faild

come inside loop to check end of file: line: script ran successfully

line found.go out of loop now

Below code prints «label update failed only once»

import java.io.File; import java.util.Scanner; /** * * @author root */ public class ReadFileScanner < public static void main(String s[]) < String log = "/tmp/ws/prakash-rcd/label" + "prakash_label_test" + ".log"; File file = new File(log); String line = null; boolean logFailureMsg = true; try < Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) < line = scanner.nextLine(); System.out.println("come inside loop to check end of file: line: " + line); if (line.contains("script ran successfully")) < System.out.println("line found.go out of loop now"); break; >else < if(logFailureMsg) < System.out.println("label update faild"); logFailureMsg = false; >> > > catch(Exception e) < e.printStackTrace(); >> > 

@Prakash.when i tried it was not working but this code works..but if the log file has many lines so this code reads all the lines one by one and prints the line «come inside loop to check logs.label update faild» so many times.is there a way to read untill the last line but print «come inside loop to check logs.label update faild» only once and not everytime the code reads a line from the log

@priyanka. outside while set boolean scriptExecutedSuccessfully = false; inside if set scriptExecutedSuccessfully = true; remove else. after while loop if(!scriptExecutedSuccessfully) < System.out.println("label update faild"); >

Источник

How to detect eof in java?

When reading data from an input stream in Java, it is important to detect the end-of-file (EOF) marker in order to properly handle the termination of the stream. There are several ways to detect EOF in Java, and it is important to understand these methods to effectively read data from input streams. In this article, we will explore the different ways to detect EOF in Java and provide an overview of each method.

Method 1: Use the read() Method

To detect EOF in Java using the read() method, you can use the following steps:

  1. Create a FileInputStream object and pass the file path as a parameter.
  2. Create a BufferedInputStream object and pass the FileInputStream object as a parameter.
  3. Create a byte array to store the data read from the file.
  4. Use the read() method of the BufferedInputStream object to read the data from the file into the byte array.
  5. Check if the value returned by the read() method is equal to -1 . If it is, then EOF has been reached.
import java.io.*; public class EOFDetector  public static void main(String[] args)  try  FileInputStream fileInputStream = new FileInputStream("file.txt"); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = bufferedInputStream.read(buffer)) != -1)  // do something with the data read from the file > bufferedInputStream.close(); > catch (FileNotFoundException e)  e.printStackTrace(); > catch (IOException e)  e.printStackTrace(); > > >

In this example, we create a FileInputStream object with the file path «file.txt» . We then create a BufferedInputStream object with the FileInputStream object as a parameter. We create a byte array with a size of 1024 to store the data read from the file. We then use a while loop to read the data from the file into the byte array using the read() method of the BufferedInputStream object. If the value returned by the read() method is equal to -1 , then EOF has been reached and the loop will exit. Finally, we close the BufferedInputStream object.

Note that the read() method returns the number of bytes read from the file, or -1 if EOF has been reached.

Method 2: Use a Scanner

To detect EOF in Java using a Scanner, you can use the hasNextLine() method. This method returns true if there is another line in the input of the Scanner and false otherwise. Here is an example code:

Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine())  String line = scanner.nextLine(); // do something with the line > scanner.close();

In this code, the while loop will continue as long as there is another line in the input of the Scanner. Once there is no more input, the loop will terminate and the Scanner will be closed.

Another way to detect EOF using a Scanner is to use the hasNext() method. This method returns true if there is another token in the input of the Scanner and false otherwise. Here is an example code:

Scanner scanner = new Scanner(System.in); while (scanner.hasNext())  String token = scanner.next(); // do something with the token > scanner.close();

In this code, the while loop will continue as long as there is another token in the input of the Scanner. Once there is no more input, the loop will terminate and the Scanner will be closed.

It is important to note that the hasNext() method will not detect the end of the input if the last token is not followed by whitespace. In this case, you can use the hasNextLine() method instead.

In summary, to detect EOF in Java using a Scanner, you can use the hasNextLine() or hasNext() method. These methods will return true if there is more input in the Scanner and false otherwise.

Method 3: Use a BufferedReader

To detect EOF in Java using a BufferedReader, you can use the readLine() method and check if it returns null. Here is an example code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = br.readLine()) != null)  // process the line > // reached the end of the input

In this code, we create a BufferedReader object br to read input from the console. We then use a while loop to read each line of input using the readLine() method. The loop continues until readLine() returns null, indicating that we have reached the end of the input.

You can also use the ready() method of BufferedReader to check if there is more input available to read. Here is an example code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (br.ready())  String line = br.readLine(); // process the line > // reached the end of the input

In this code, we use a while loop to check if there is more input available using the ready() method. If there is, we read the next line using readLine() and process it. The loop continues until there is no more input available.

Note that the ready() method may not work correctly with some types of input streams, so using readLine() and checking for null is generally more reliable.

Источник

How to identify end of InputStream in java

I am trying to read bytes from server using Socket program, ie I am using InputStream to read the bytes. If I pass the length size I am able to read the bytes, but I am not sure what may be the length. So I am not able initialize the byte array. Also I tried while (in.read() != -1) , I observered it loop works fine when the data is sent, but the next line after the loop is not executable, I feel its still looking for the data in the stream but there is no data. If I close the Server connection, then my client will execute the next line followed to the loop. I am not sure where I am going wrong?

this.in = socket.getInputStream(); int dataInt = this.in.read(); while(dataInt != -1) < System.out.print(","+i+"--"+dataInt); i++; dataInt = this.in.read(); >System.out.print("End Of loop"); 
,1--0,2--62,3--96,4--131,5--142,6--1,7--133,8--2,9--16,10--48,11--56,12--1,13--0,14--14,15--128,16--0,17--0,18--0,19--48,20--0,21--0,22--0,23--0,24--0,25--1,26--0,27--0,28--38,29--114,30--23,31--20,32--70,33--3,34--20,35--1,36--133,37--48,38--51,39--49,40--52,41--49,42--55,43--49,44--52,45--52,46--54,47--55,48--50,49--51,50--52,51--48,52--53,53--56,54--51,55--48,56--48,57--57,58--57,59--57,60--57,61--57,62--57,63--57,64--56 

But no output for :- End Of loop Please guide how shall I close the loop? Looking forward for you response. Thanking you all in advance.

8 Answers 8

It’s looking for more data because nothing’s told it that there won’t be more data. The other end of the network could send more data at any time.

It’s not clear whether you’re designing the client/server protocol or just trying to implement it, but typically there are three common ways of detecting the end of a message:

  • Closing the connection at the end of the message
  • Putting the length of the message before the data itself
  • Using a separator; some value which will never occur in the normal data (or would always be escaped somehow)

Personally I favour length-prefixing when possible; it makes the reading code significantly simpler, but still allows multiple messages on the same connection.

(Additionally, I agree with Daniel that you should be using the overload of read which reads a whole buffer at a time, instead of a single byte. This will be much more efficient — but doesn’t fundamentally change the nature of your current issue.)

I am the client trying to pass some data to server. The server will respond in the bytes, I am trying to read this bytes. The server is already created & maintaned by some one else. Here my doubt would be when the server has responsded it has to close If I am not wrong. Also How would I close the connection (Client) as I am still not able to identify that I have read the complete response

@Vardhaman: It entirely depends on the protocol. I wasn’t suggesting that the reading side should close the connection — the writing side (the server in this case) should close its connection, at which point you’ll see the end of the data. But that’s only if the protocol is designed that way. what protocol is it using?

@Vardhaman: It’s not just TCP though. There’s a higher level protocol involved, which describes the format of the messages, the control flow etc. You should ask «them» what the expected behaviour is.

@ikzjfr0: Well I’m not going to pore over the code to understand how. TCP/IP is a stream-based protocol; anything over that has to take account of it. Now a library on top of it can potentially do the message-length-prefixing for you, but that doesn’t remove the need for it. it just does it for you. Those are very different.

I think you’ve actually answered your own question.

The reason you are not exiting the loop is that the end of input stream only happens on the client end after the server end closes its socket. (Or more precisely, after it closes its socket output stream . or the equivalent . and the close event has propagated to the client end.)

Until that event happens, it is possible that the server could decide to write more data to the socket. So the client-side read blocks . until it either gets more data or it sees the protocol event that says that the server end has closed.

(Actually, other events can unblock the client read, but they will all result in an IOException of some kind, and probably a stream that you can’t read any more data from.)

Now, if you don’t want to close the server end now because you want to send more stuff on the socket later on, you are going to have to change your application protocol to use some kind of framing mechanism. For instance, the server might send a frame (or record, or whatever) consisting of byte count followed by the given number of bytes. Alternatvely, it could use a distinguished byte value or byte sequence to mark the end of a frame.

Источник

Читайте также:  Append html with javascript
Оцените статью