상대 경로 : 내 파일(프로젝트폴더)에 위치를 기반으로 경로를 정하는 것
절대 경로 : 루트에서 부터 경로를 찾는것
윈도우 에서 경로 찾는법 : C:\\workspace\\hello.txt, 자바에서 \\는 뒤에 문자를 무시하기 때문에 \\\\두개써야함
맥, 리눅스 에서 경로 찾는법 : /workspace/hello.txt
예제
package ex15;
import java.io.IOException;
import java.io.InputStream;
public class StreamEx01 {
public static void main(String[] args) {
InputStream input = System.in; // System.in : 키보드로 부터 인풋을 받음
try {
int value = input.read();
System.out.println("받은 값 : " + (char) value);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
// a b 입력시 a만 나옴
package ex15;
import java.io.IOException;
import java.io.InputStreamReader;
public class StreamEx02 {
public static void main(String[] args) {
InputStreamReader ir = new InputStreamReader(System.in);
char[] ch = new char[4];
try {
ir.read(ch); // 보조 스트림
for (char c : ch) {
System.out.print(c + " ");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
// ch 의 크기만큼만 출력
버퍼 사용 예제
package ex15;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StreamEx03 {
public static void main(String[] args) {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
try {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
// String 처럼 크기가 유동적임
package ex15;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class StreamEx04 {
public static void main(String[] args) {
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(System.out)
);
try {
// \\n은 readLine에서 읽을 때 ;과 똑같다. 안써주면 못읽는다.
// \\n은 통신의 가장 마지막에 붙혀준다.
bw.write("안녕\\n"); // 내려쓰기 가능
bw.write("반가워\\n"); // readLine이 읽을 때, \\n 을 끊어서 읽기 때문에 두 번 읽어줘야한다.
bw.flush(); // 플러시 해줘야함 안해주면 출력이 안됌
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
package ex15;
import java.io.*;
// 상대 경로 : 내 파일(프로젝트폴더)에 위치를 기반으로 경로를 정하는 것
// 절대 경로 : 루트에서 부터 경로를 찾는것
// 윈도우 에서 경로 찾는법 : C:\\workspace\\hello.txt, 자바에서 \\는 뒤에 문자를 무시하기 때문에 \\\\두개써야함
// 맥, 리눅스 에서 경로 찾는법 : /workspace/hello.txt
public class StreamEx05 {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
//inputStream = new BufferedReader(new FileReader("D:\\\\workspace\\\\java_lec\\\\study\\\\out\\\\production\\\\study\\\\ex15\\\\input.txt"));
inputStream = new BufferedReader(new FileReader
("src\\\\ex15\\\\input.txt"));
outputStream = new PrintWriter(new FileWriter
("src\\\\ex15\\\\output.txt"));
String i;
while ((i = inputStream.readLine()) != null) {
outputStream.println(i);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
// input에 쓰인 문자열을 output에 덮어씀