Solved

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

Posted on 2003-10-27
15
278 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
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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
mockito example issue 8 62
eclipse argument 14 53
diffSum example 4 26
Why my table column Id is not passed to java object? 4 26
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 how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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…

895 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

14 Experts available now in Live!

Get 1:1 Help Now