PDA

View Full Version : đọc ghi lên file



thanh dat
20-10-2005, 11:02
mọi người ơi , giúp em với , đoạn code này lỗi , làm sao để sửa cho đúng đây :

package File;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class XuLyFile extends Object
{
//ghi ngau nhien cac phan tu , so phan tu biet truoc
public void ghiNgauNhien(String duongdan,int sopt) throws IOException
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(duongdan));

for(int i=1;i<=sopt;i++)
{
dos.writeInt(1+(int)(Math.random()*1000)); // ghi phan tu ngau nhien
}
dos.close();
}

// nhap tung phan tu , ghi vao file , so phan tu biet truoc
public void nhapTrucTiep(String duongdan,int sopt) throws IOException
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(duongdan));

for(int i=1;i<=sopt;i++)
{
String giatri;
giatri = JOptionPane.showInputDialog("Number "+ i);//nhap so
if (giatri == null ) // neu khong nhap coi nhu so do = 0
giatri = "0";
dos.writeInt(Integer.parseInt(giatri)) ;
}
dos.close();
}

//hien noi dung file ra TextArea , duong dan file biet truoc
public void hien(String duongdan,TextArea t) throws IOException
{
DataInputStream dis = new DataInputStream(new FileInputStream(duongdan));
boolean eof;
eof = false;

while (!eof)
{
if(dis.read()==-1) eof = true; //het file
else
{
String giatri;
giatri = dis.readInt() + "\n" ;
t.append(giatri) ;
}
}
}

public static void main(String a)
{
XuLyFile x = new XuLyFile();
TextArea t = new TextArea(15,10);

x.ghiNgauNhien("a1.txt",10);
x.nhapTrucTiep("a2.txt",10);
x.hien("a1.txt",t);
x.hien("a2.txt",t);
}
}