Solved

how to read and re-write a line in a file?

Posted on 2003-10-27
15
281 Views
Last Modified: 2010-03-31
Dear experts,

My application needs to test the first line of the file it reads. If there is space before the first char of the first line, I need to "move" the whole line forward, which means get rid of the space in front. What is the right way of doing this? thanks.
0
Comment
Question by:changcy77
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 4
15 Comments
 
LVL 5

Accepted Solution

by:
lwinkenb earned 40 total points
ID: 9631019
FileInputStream fis = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis);

String line = br.readLine();
String file = line;

if(line.charAt(0) == ' ') {
  while((line = br.readLine()) != null)
    file += line;
  file = file.substring(1);
  br.close();
  FileOutputStream fos = new FileOutputStream("file.txt");
  PrintWriter outFile = new PrintWriter(fos);
  outFile.print(file);
  outFile.close();
}
else {
  br.close();
}
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9631031
also you can also replace
file = file.substring(1);
with
file = file.trim();
if you want to remove all the whitespace at the beginning and end of the file.
0
 

Author Comment

by:changcy77
ID: 9631040
so, your solution is re-write the whole file instead of just re-write one line? Is it possible to just do one line, which might save some effort?
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 5

Expert Comment

by:lwinkenb
ID: 9631431
>>Is it possible to just do one line, which might save some effort?
No, not possible.
0
 
LVL 5

Assisted Solution

by:mrigank
mrigank earned 20 total points
ID: 9631945
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20733355.html

public static void main(String args[])    throws Exception
{
   RandomAccessFile f = new RandomAccessFile("d:\\file.txt","rw");

   String firstLine = f.readLine();
   int length = firstLine.length();
   while(firstLine.substring(0,1).equalsIgnoreCase(" ") && firstLine.length() > 1)
   {
      firstLine = firstLine.substring(1);
   }
    f.seek(0);

   int newLength = firstLine.length();
   if(length != firstLine.length())
   {
     System.out.println("White Spaces :: " + (length - newLength));
     byte b[] = new byte[(new Long(f.length())).intValue()];
     f.readFully(b);
     f.seek(0);
     String allFile = new String(b);
     String newFile = allFile.substring(length - newLength);
     f.writeBytes(newFile);
     f.seek(0) ;
     f.setLength((new Long(f.length())).intValue() - (length - newLength));
   }
    f.close();
  }
}

0
 
LVL 5

Expert Comment

by:mrigank
ID: 9631953
You can do the required action in one go in the above case ...
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9632164
That code has a lot more overhead than the code I posted.

Instead of reading the file to a string then rewriting it, you are reading part of the file to a string, then reading the whole file to a byte array, then copying that byte array to a string, then copying that string to another string, then writing that string back to the file.
0
 
LVL 5

Expert Comment

by:mrigank
ID: 9632181
My code definitely has overheads ... in fact if the file is in kbs and mbs then the entire file cannot be read also at once ... i posted the code in case simultaneous read and write is required ....
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9632409
I have no problem with people posting alternative solutions, that is what makes experts-exchange great :)

>>in fact if the file is in kbs and mbs then the entire file cannot be read also at once
That depends on how much RAM the user has.  Most people wouldnt have any problem loading a file that is multiple MB into memory.

>>i posted the code in case simultaneous read and write is required
RandomAccessFile is good for when you want to append or overwite files.  It is substantially slower than BufferedReader, so it is best to use BufferedReader if you have to read the whole file into memory (which both of our examples do).
0
 
LVL 5

Expert Comment

by:mrigank
ID: 9632706
>>I have no problem with people posting alternative solutions, that is what makes experts-exchange great :)

yup ... agreed :) ...

and thanks for your input on BufferedReader and RandomAccessFile :) ....
0
 

Author Comment

by:changcy77
ID: 9651707
Thanks to all input. However, when I use

 file+=line;

I found the trailing space of the first line "disappeared". How could I keep the trailing space when I also concatenate two strings? thanks again.
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9651824
sorry, you should change:

while((line = br.readLine()) != null)
    file += line;

to the following:

file = br.readLine();
while((line = br.readLine()) != null)
    file += "\r\n" + line;

0
 

Author Comment

by:changcy77
ID: 9651862
Thanks.

So, string concatenation just "naturally" delete the trailing spaces?  
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9651970
the problem wasnt that it was deleting trailing spaces, the problem was that it didnt include the new line characters (\r\n).    When you call br.readLine(), it returns the string up to the new line characters, but it doesnt include them.  So when you concat all these strings together, you are missing those.  So if the file looked like:

this file should have
new line characters
placed at the end
of each line.

then without adding in the "\r\n" it looks like:

this file should havenew line charactersplaced at the endof each line.
0
 

Author Comment

by:changcy77
ID: 9653237
thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mysql jsp example issue 32 96
glassfish admin console 1 52
wild fly 8 startup error 2 82
Hibernate Inheritance Strategy for Abstract Base class and two concrete classes 3 39
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Suggested Courses

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question