-
File processing using Java
Hi, I am having trouble with writing multiple records to an output file. I am able to read multiple records from the input file and make some modifications to the individual tokens of the file but when writing to a file, I am overwriting the previous records and thus am able to display only the last record in the output file. How can I write all records from my input file to the output file?
When I use the PrintWriter class as follows,
PrintWriter out = new PrintWriter(new
FileWriter("sri2.dat", true))
I am able to write only the last record (twice). I am
not able to write the records before the last record.
How can I write all the records from the input file
into the output file?
Thanks a lot for your help.
My current code is as follows:
_____________________________________________
import java.io.*;
import java.util.*;
class inputFile
{
private String ordDate;
private String ordNum;
private String custName;
private String custDesc;
private String ccType;
private String newccType;
private String expDate;
public inputFile()
{}
public void readData(BufferedReader in) throws
IOException
{
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, "|");
ordDate = t.nextToken();
ordNum = t.nextToken();
custName = t.nextToken();
custDesc = t.nextToken();
ccType = t.nextToken();
if (ccType.equals("V") )
newccType = "VI";
expDate = t.nextToken();
System.out.println(ordDate);
}
public void writeData(PrintWriter out) throws
IOException
{
out.println(ordDate + "|" +
ordNum + "|" +
custName + "|" +
custDesc + "|" +
newccType + "|" +
expDate);
}
}
class readFile2
{
public static void main(String args[])
{
inputFile inp = new inputFile();
// Read the input file
try
{
BufferedReader in = new BufferedReader(new
FileReader("orders.dat"));
//inputFile ipf = readData(in);
inp.readData(in);
in.close();
}
catch(IOException e)
{
System.out.print("Error reading from the file : " +
e);
System.exit(1);
}
// Write the contents to a new file
try
{
PrintWriter out = new PrintWriter(new
FileWriter("sri2.dat", true));
inp.writeData(out);
out.close();
}
catch(IOException e)
{
System.out.print("Error reading from the file : " +
e);
System.exit(1);
}
}
}
_____________________________________________
-
You're asking way too many questions at once. If I understand it you want to be able to append to a file rather than overwriting its contents each time. To do this you need to use the following constructor of FileOutputStream:
FileOutputStream(String name, boolean append)
If you pass in 'true', it will append to the file.
ArchAngel.
O:-)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|