1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
package com.io.controller;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileIOStreamTest {
Scanner sc = new Scanner(System.in);
public void saveFile() {
//OutputStream : 램에 있는걸 빼서 저장하는 것이기 때문에
//Stream은 반드시 반환 -> close() 메서드 사용
// 예외처리 해야함 -> try ~ catch 이용
FileOutputStream out = null;
try {
out = new FileOutputStream("testpath.txt");
String msg = "lambda fighting 123";
//write() 메서드 이용해서 파일 전송
byte[] data = msg.getBytes();
out.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(null!=out) {
out.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
public void loadFile() {
//InputStream :
FileInputStream fis = null;
try {
fis = new FileInputStream("testpath.txt");
int data = -1; //가져온 byte 데이터를 보관하는 변수
//inputStream에서 파일에 저장된 내용을 더 이상 가져올게 없으면 -1 반환
while((data=fis.read())!=-1) {
System.out.println((char)data);
}
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if(fis!=null)fis.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
public void strSaveFile() {
try(FileWriter out = new FileWriter("strData")){
String str = "춥고 배고프다 ";
out.write(str);
out.write("우동 한 그릇");
} catch(IOException e) {
e.printStackTrace();
}
}
public void strLoadFile() {
try(FileReader fr = new FileReader("strData")){
int data = -1;
String msg = "";
while((data=fr.read())!=-1) {
msg+=(char)data;
}
System.out.println(msg);
}catch(IOException e) {
e.printStackTrace();
}
}
String txt = "";
public void saveText() {
System.out.print("파일명을 입력하시오 : ");
txt = sc.nextLine();
try(FileWriter out = new FileWriter(txt)){
boolean flag = true;
String msg = "";
do {
String add = sc.nextLine();
if(add.equals("exit")) {
flag = false;
break;
}
msg = msg+add;
} while(flag);
out.write(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadText() {
try(FileReader fr = new FileReader(txt)){
int data = -1;
String msg = "";
while((data=fr.read())!=-1){
msg += (char)data;
}
System.out.println(msg);
}catch(IOException e) {
e.printStackTrace();
}
}
}
|
cs |
'KH정보교육원_웹 프로그래머 과정 > Java' 카테고리의 다른 글
스레드 Thread (0) | 2021.02.23 |
---|---|
제너릭스 Generics (0) | 2021.02.23 |
입출력 IO (0) | 2021.02.17 |
예외처리 Exception (0) | 2021.02.16 |
String 관련 클래스 (0) | 2021.02.10 |