import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
class Sung{
private String pathname="sung.txt";
private Scanner sc=new Scanner(System.in);
public void readFile(){
File f=new File(pathname);
if(! f.exists()){
return;
}
String hak, name;
int kor, eng, mat;
DataInputStream dis=null;
try{
dis=new DataInputStream(new FileInputStream(f));
while(true){
hak=dis.readUTF();
name=dis.readUTF();
kor=dis.readInt();
eng=dis.readInt();
mat=dis.readInt();
String s=String.format("%10s\t%10s\t%5d%5d%5d",hak,name,kor,eng,mat );
System.out.println(s);
}
}catch(EOFException e){
// DataInputStream 스트림은 파일의 끝에 도달하면 EOFException 예외가 발생한다.
// 따라서 EOFException 예외가 발생하면 문제가 있는 것이 아니라 파일의 내용을 다 읽어드린 것이다.
}catch(Exception e){
}
}
public void writeFile() {
String hak, name;
int kor, eng, mat;
DataOutputStream dos=null;
try{
// 파일이 있으면 지우고 없으면 만듬
// dos=new DataOutputStream(new FileOutputStream(pathname)); // 하나의 데이터만 저장되는 문제가 생긴다.
//파일이 있으면 추가하고 없으면 만듬
dos=new DataOutputStream(new FileOutputStream(pathname,true));
System.out.print("학번?");
hak=sc.next();
System.out.print("이름?");
name=sc.next();
System.out.print("국어?");
kor=sc.nextInt();
System.out.print("영어?");
eng=sc.nextInt();
System.out.print("수학?");
mat=sc.nextInt();
dos.writeUTF(hak);
dos.writeUTF(name);
dos.writeInt(kor);
dos.writeInt(eng);
dos.writeInt(mat);
dos.close();
}catch(Exception e){
}
}
}
public class Test2 {
public static void main(String[] args) {
Sung s=new Sung(); // 참조변수를 만들 때 사용하는 Sung(); 이게 생성자다
char ch;
try{
while(true){
do{
System.out.print("1.불러오기 2.저장 3.종료=>");
ch=(char)System.in.read();
System.in.skip(2);
}while(ch<'1'||ch>'3');
switch(ch){
case '1': s.readFile();break;
case '2': s.writeFile();break;
case '3': System.exit(0); break;
}
}
}catch(Exception e){
}
}
}
'자바 DB 연동 > 입출력 스트림' 카테고리의 다른 글
RandomAccessFile (0) | 2013.06.19 |
---|---|
DataOutputStream / DataInputStream (0) | 2013.06.15 |
BufferedInputStream / BufferedOutputStream (0) | 2013.06.14 |
File 클래스 - 폴더만들기, 파일정보구하기 (0) | 2013.06.14 |
flush 메소드 (0) | 2013.06.14 |