Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2003-10-27
15
Medium Priority
?
283 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 160 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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
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 80 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.
Suggested Courses

705 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