**반드시 기억하기**
ANSI(ISO-8859-1, EUC-KR, MS949)
1. 영어(숫자, 특수문자, 서유럽 등): 1byte
2. 한글(한자, 일본어 등): 2byte
UTF-8(Unicode) > 국제 표준*
1. 영어: 1byte
2. 한글: 3byte
UTF-16(Unicode)
1. 영어: 2byte
2. 한글: 2byte
try {
File file = new File("C:\\class\\code\\java\\file\\list.txt");
//스트림 객체 생성 == '스트림 열기' 라고 표현한다.
FileOutputStream stream = new FileOutputStream(file);
stream.write(65); //A
stream.write('홍'); //한글 깨진다.
String txt = "hello~!";
for (int i=0; i<txt.length(); i++) {
char c = txt.charAt(i);
stream.write(c);;
}
//스트림 닫기
stream.close();
System.out.println("종료");
} catch (Exception e) {
System.out.println("at Ex65_File.m1");
e.printStackTrace();
}
try {
FileWriter writer = new FileWriter("C:\\class\\code\\java\\file\\member.txt");
writer.write("한글"); //문자열을 한번에 저장 가능
writer.close();
System.out.println("종료");
} catch (Exception e) {
System.out.println("at Ex65_File.m3");
e.printStackTrace();
}
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("C:\\class\\code\\java\\file\\memo.txt"));
bwriter.write("하나");
bwriter.write('A');
bwriter.write("\r\n"); //엔터
bwriter.write("둘");
bwriter.newLine(); //엔터
bwriter.write("셋");
bwriter.close();
System.out.println("종료");
} catch (Exception e) {
System.out.println("at Ex65_File.m5");
e.printStackTrace();
}
try {
//읽기 스트림 객체
FileInputStream stream = new FileInputStream(Ex65_File.FILE);
int code = -1; //파일내에 읽을 글자가 없으면 -1 반환
while((code = stream.read()) != -1) {
System.out.print((char)code);
}
System.out.println();
stream.close();
} catch (Exception e) {
System.out.println("at Ex65_File.m2");
e.printStackTrace();
}
try {
FileReader reader = new FileReader("C:\\class\\code\\java\\file\\member.txt");
int code =-1;
while((code=reader.read())!=-1) {
System.out.print((char)code);
}
System.out.println();
reader.close();
System.out.println("종료");
} catch (Exception e) {
System.out.println("at Ex65_File.m4");
e.printStackTrace();
}
try {
BufferedReader breader2 = new BufferedReader(new FileReader("C:\\class\\code\\java\\file\\memo.txt"));
String line = null;
while ((line=breader2.readLine())!=null) {
System.out.println(line);
}
breader2.close();
System.out.println("종료");
} catch (Exception e) {
System.out.println("at Ex65_File.m6");
e.printStackTrace();
}
try {
Scanner scan = new Scanner(System.in);
System.out.print("저장할 파일명: ");
String fileName = scan.nextLine();
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\class\\code\\java\\file\\" + fileName + ".txt"));
while (true) {
System.out.print("입력: ");
String line = scan.nextLine();
//"exit" 입력받으면 입력 종료
if (line.equals("exit")) {
break;
}
writer.write(line); //한줄을 입력받아서 한줄 쓰기(writer)
writer.write("\r\n");
}
writer.close();
System.out.println("파일 저장 완료");
} catch (Exception e) {
System.out.println("at Ex65_File.m7");
e.printStackTrace();
}