import java.io.*;
import java.util.*;
public class InputStreamPractice {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("읽을 파일 : ");
String src = scan.nextLine();
System.out.println();
System.out.println("=========");
System.out.println();
try (Reader reader = new FileReader(src)) {
int ch;
while (true) {
ch = reader.read();
if (ch == -1) {
break;
}
System.out.print((char) ch);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
[Console]
OutputStreamPractice.java (BufferedWriter 내용 작성)
import java.io.*;
import java.util.*;
public class OutputStreamPractice {
public static void main(String[] args) throws IOException {
String koreanString = "공부에 있어서 돈이 꼭 필요한 것은 아니다.";
String englishString = "Life is long if you know how to use it.";
try (BufferedWriter bw = new BufferedWriter(new FileWriter("String.txt"))) {
bw.write(koreanString, 0, koreanString.length());
// Writer에 해당하는 한국어 문자열을 처음부터 끝까지 쓴다 (index= 0 ~ 문자열의 총 길이까지)
bw.newLine(); // 한줄 개행
bw.write(englishString, 0, englishString.length());
// 영어 문자열도 쓴다.
} catch (Exception e) {
e.printStackTrace();
}
}
}
InputStreamPractice.java (BufferedReader 내용 작성)
import java.io.*;
import java.util.*;
public class InputStreamPractice {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader("String.txt"))) {
String str;
while (true) {
str = br.readLine(); // Reader로 라인을 읽어온다.
if (str == null) {
break;
} // 아무 것도 없으면 그만하기
System.out.println(str); // String 출력하기
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
싱글 스레드 : 먼저 시작한 작업이 끝나야 다음 작업을 할 수 있다.
public class JavaTest {
public static void main(String[] args) {
for (int i = 0; i < 300; i++) {
System.out.println("-");
}
for (int i = 0; i < 300; i++) {
System.out.println("|");
}
}
}
멀티 스레드 : 함수 객체로 구현되어 동시에 작업할 수 있도록 만들어졌다. (구현한 것이 섞여서 출력된다.)
class MyThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 300; i++) {
System.out.println("-");
}
}
}
class MyThread2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 300; i++) {
System.out.println("|");
}
}
}
public class JavaTest {
public static void main(String[] args) {
MyThread1 th1 = new MyThread1();
MyThread2 th2 = new MyThread2();
th1.start();
th2.start();
}
}