同じテキストファイルを同時に読み書きすることはできますか?同じファイルへの書き込みと読み取り
最初のスレッドはファイルにテキスト文字列を追加し、データがない場合は "ending"文字列を追加します。
2番目のスレッドは、そのファイルからデータを読み込み、新しいデータがある場合はブロックします。それは "終了"文字列を読むときに終了する必要があります。
public class TheFileReader implements Runnable {
public void run() {
FileInputStream is = null;
BufferedReader fbr = null;
File file = new File ("C:\\temp\\fileout3.txt");
String s1 ="";
try {
fbr = new BufferedReader(new FileReader(file), 1024*1024);
while (s1.equals("exit")==false){
s1 =fbr.readLine();
if (s1==null){
s1="";
Thread.sleep (50);
}
else
System.out.println(s1);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally
{
try {
fbr.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class TheFileWriter implements Runnable {
public void run() {
FileOutputStream os = null;
BufferedWriter fbw = null;
File file = new File ("C:\\temp\\fileout3.txt");
String s1 ="";
try {
fbw = new BufferedWriter(new FileWriter(file), 1024*1024);
for (int i = 0; i < 100; i++) {
fbw.write("test" + i);
fbw.newLine();
}
fbw.write("exit");
} catch (IOException e) {
e.printStackTrace();
} finally
{
try {
fbw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
UPDATE:
私はfbw.flush() after fbw.newLine();
を追加する場合、私はそれが動作すると思います。
データベースを設計しようとしているようです。代わりに本物のものを使いたいかもしれません。 – toto2
次の質問と同じように見えます:http://stackoverflow.com/questions/8607169/file-reading-writing-using-multithreading/8607215#8607215 –