Salve ragazzi vorrei un consiglio:
sto cercando di implementare un pezzo di code che ha il compito di leggere e scrivere delle informazioni su file .txt. Il codice ha la seguente logica:
Se il file .txt non è stato gia creato ( quindi non si trova nella directory) allora ne creo uno nuovo e ci inserisco dei dati.
Se il file .txt esiste gia allora non deve modificare i dati che gia ci sono ma deve aggiungerne altri.
Vorrei un consiglio su questo ultimo punto. Ho scritto già del codice che posto qui sotto. Io avrei in mente di copiare (leggere) quello che gia c'e nel file ( se non esiste gia) e aggiungere i nuovi dati...che ne dite.???? ammesso che vada bene come soluzione come potrei farla nei migliori dei modi??? thx
codice:
import java.io.*;
import java.util.*;
public class DataFileTest {
public static void main(String[] args) throws IOException {
String[] staff = new String[1];
try {
BufferedReader in = new BufferedReader(new FileReader("prova.txt"));
String[] newStaff = readData(in);
System.out.println(newStaff[0]);
in.close();
} catch (FileNotFoundException ex) {
try {
PrintWriter out = new PrintWriter(new FileWriter("prova.txt"));
writeData(staff, out);
out.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
static void writeData(String[] e, PrintWriter out) throws IOException
{
// write number of employees
out.println(e.length);
for (int i = 0; i < e.length; i++)
out.println("var1"+"|"+"var2"+"|"+"var4");
}
static String[] readData(BufferedReader in) throws IOException
{
// retrieve the array size
int n = Integer.parseInt(in.readLine());
String[] e = new String[n];
for (int i = 0; i < n; i++)
{
e[i] = new String();
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, "|");
String name1 = t.nextToken();
String name2 = t.nextToken();
String name3 = t.nextToken();
e[i]=s;
}
return e;
}
private String name;
private double salary;
private Date hireDay;
}