Article View: borland.public.jbuilder.java.language
Article #8370Re: Write a line
From: Paul Linehan
Date: Tue, 27 Mar 2001 13:21
Date: Tue, 27 Mar 2001 13:21
87 lines
2530 bytes
2530 bytes
Ahmad Noori <Ahmad.Y.Noori@SAIC.COM> wrote:
> Hello,
> I have a txt file that I want to write to it one line at a time. I
> sometimes want to write in the middle of the file and sometimes at the
> beginning. Using write(string, int, int), will replace the whole file,
> readline() reads one line at a time, does anyone knowof a method that
> could write one line at a time.
Try this - there is no way to avoid writing stuff out and in all the
time - sorry, but that's just a fact of life - but hey, disks are
cheap these days...
Paul...
public static void insertStringInFile(String inFilename,
int lineno,
String lineToBeInserted)
throws IOException
{
// temp file
File outFile = new File("$$$$$$$$.tmp");
// input
File inFile = new File(inFilename);
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader (new InputStreamReader(fis));
// output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
// System.out.println("Putils: Insertion is at line *_" + lineno + "_*");
for(int i = 1; i < lineno; i++)
{
thisLine = in.readLine();
out.println(thisLine);
}
out.println(lineToBeInserted);
while ((thisLine = in.readLine()) != null)
{
out.println(thisLine);
}
out.flush();
out.close();
in.close();
inFile.delete();
outFile.renameTo(inFile);
}
> Thanks a lot
>
> Ahmad Noori
> SAIC
>
>
Technical Details
Message-ID:
<3ac09385.1218646140@newsgroups.borland.com>Path:
arc1-ca.pugleaf.net!supernews.google.com!sn-xit-03!supernews.com!cyclone2.usenetserver.com!news-out.usenetserver.com!news.tele.dk!194.213.69.151!news.algonet.se!algonet!newsfeed1.uni2.dk!newssuck.uni2.dk!dnews!193.120.178.201References:
<3ABF903A.54E8FC0@SAIC.COM>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,95abce2b73e81abc X-Google-Attributes: gidf74b3,public X-Google-ArrivalTime: 2001-03-27 07:42:02 PST From: paul@esat.net (Paul Linehan) Newsgroups: borland.public.jbuilder.java.language Subject: Re: Write a line Date: Tue, 27 Mar 2001 13:21:49 GMT Message-ID: <3ac09385.1218646140@newsgroups.borland.com> References: <3ABF903A.54E8FC0@SAIC.COM> X-Newsreader: Forte Free Agent 1.21/32.243 NNTP-Posting-Host: 193.120.178.201 X-Trace: 27 Mar 2001 05:23:15 -0800, 193.120.178.201 Lines: 88 Path: arc1-ca.pugleaf.net!supernews.google.com!sn-xit-03!supernews.com!cyclone2.usenetserver.com!news-out.usenetserver.com!news.tele.dk!194.213.69.151!news.algonet.se!algonet!newsfeed1.uni2.dk!newssuck.uni2.dk!dnews!193.120.178.201