hub
hub

Reputation: 101

How to remove empty line while reading a file

I would like know how I can remove a blank line while reading/writing a file?

for(int i=1;i<=count;i++) {
    FileInputStream fistream1;
    try {
        name1="file1"+Integer.toString(i)+".txt";
        fistream1 = new FileInputStream(name1); // first source file
        fistream2 = new FileInputStream("Result.txt");  //second source file
        sistream = new SequenceInputStream(fistream2, fistream1);  
        fostream= new PrintWriter(new BufferedWriter(new FileWriter( result+".txt", true)));

        while( ( temp = sistream.read() ) != -1) {
            fostream.write(temp);   // to write to file
        }

        fostream.println("");
        fostream.close();
        sistream.close();
        fistream1.close();
        fistream2.close();
}

I found this code but I couldn't implement it because of following line:

String line;
while((line = br.readLine())!= null) { ... }

They have used line as a String, but in my case I have temp as int:

int temp;
while((temp = sistream.read())!=-1) { ... }

Is there a way to solve this problem?

The answer of @Abdelhak is not acceptable.

Upvotes: 1

Views: 885

Answers (2)

hub
hub

Reputation: 101

The solution was so simple.

I should read lines instead of reading bytes to determine if a line is empty and used a BufferedReader on conjunction with SequenceInputStream.

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

You can try something like this:

while( ( temp = sistream.read() ) != -1) {
  if (!temp.trim().equals(""))
  {
    fostream.write(temp); // to write to file
  }
...

Upvotes: 1

Related Questions