writing data in text file..

1. check the file name in D:\\temp\\test.txt

2. if it exists, then open file. if there is data, then read data. after the last record, it writes new data.

3. if it does not exist, create text.txt file and write data into text.txt file.

so far, I have a code..

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

String filename="test";

String format = "%1$-9s%2$-3s%3$-30s%4$-30s%5$-30s\n";

String arraydata[] = { "John", "F.", "Kennedy", " ", "t", "John2", "F2.", "Kennedy2", " ", "t2"};

String cnt_id ="2";

int cnt_orderid = Integer.valueOf(cnt_id);

try

{

PrintStream ps = new PrintStream(new FileOutputStream("D:\\temp\\"+filename+".txt"));

for (int i=1; i<cnt_orderid; i++)

{

ps.println(String.format(format, (Object[])arraydata)); // write in test.txt file

}

ps.close();

}

catch (Exception e)

{

System.out.println(e);

}

}

}

my question is..

1. how to check the file exists or not

2. how to write the data in the new line after the last data in the file.>

[1207 byte] By [warapa] at [2007-11-27 8:45:33]
# 1

1. Use a File object.

File file = new File("someFile.txt");

if (file.exists()) { ... }

2. Consider using FileWriter; the constructor allows you to append to the end of the file:

FileWriter fileWriter = new FileWriter(file, true);

Michael

mbishop78a at 2007-7-12 20:46:44 > top of Java-index,Java Essentials,New To Java...
# 2
Check out the java.io.File API http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.htmlspecially the boolean method exists()Manuel Leiriato slow...Message was edited by: manuel.leiria
manuel.leiriaa at 2007-7-12 20:46:44 > top of Java-index,Java Essentials,New To Java...
# 3
it works...i usedPrintStream ps = new PrintStream(new FileOutputStream(testPath+test, true));Message was edited by: warap
warapa at 2007-7-12 20:46:44 > top of Java-index,Java Essentials,New To Java...