Solved

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

Posted on 2003-10-27
15
277 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
  • 7
  • 4
  • 4
15 Comments
 
LVL 5

Accepted Solution

by:
lwinkenb earned 40 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
>>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
Comment Utility
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
Comment Utility
You can do the required action in one go in the above case ...
0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 5

Expert Comment

by:mrigank
Comment Utility
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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks.

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

Expert Comment

by:lwinkenb
Comment Utility
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
Comment Utility
thanks.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
countHi2 challenge 7 43
wordlen challenge 3 46
firstChar challenge 13 82
JList custom Cell Renderer refresh 15 38
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

763 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now