
Do it! 자바 완전 정복
File file1 = new File("C:\\Users\\wkdwl\\OneDrive\\java4\\JAVA\\Temp\\infile.txt");
try {
InputStream fis1 = new FileInputStream(file1);
int data;
while ((data = fis1.read()) != -1) {
System.out.println((char) data);
}
fis1.close();
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
}
System.out.println("\n\n");
try {
InputStream fis2 = new FileInputStream(file1);
byte[] byteArr = new byte[6];
int count1;
while ((count1 = fis2.read(byteArr))!= -1) {
System.out.println("byteArr : " + Arrays.toString(byteArr));
for(int i = 0; i < count1; i++) {
System.out.print((char) byteArr[i]);
}
System.out.println();
System.out.println("count1 :" + count1);
}
fis2.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("\n\n");
try {
InputStream fis3 = new FileInputStream(file1);
byte[] byteArr3 = new byte[9];
int offset = 3; //처음 3개는 아무것도 없는 문자 나옴
int len = 6; // 오프셋 이후 지정한 길이만큼 읽어옴
int count2 = fis3.read(byteArr3, offset, len);
for(int i = 0; i < offset+count2; i++) { //"i < offset+count2" 오프셋 길이 + 우리가 읽어들인 개수를 출력해주기 위함
System.out.println((char) byteArr3[i]);
}
fis3.close(); //자원을 항상 반납해야함.
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
File kofile = new File("C:\\Users\\wkdwl\\OneDrive\\java4\\JAVA\\Temp\\kofile.txt");
try {
InputStream fsi1 = new FileInputStream(kofile);
byte[] byteArr = new byte[8];
int count1;
while ((count1 = fsi1.read(byteArr)) != -1) {
String str = new String(byteArr, 0, count1, Charset.forName("UTF-8"));
//UTF-8로 변환했지만 그래도 깨짐 따라서 "reader"로 한글을 읽어들이는게 좋음.
System.out.println("한글 출력 : " + str);
System.out.println(" : count1 =" + count1);
}
fsi1.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
File rwfile = new File("C:\\Users\\wkdwl\\OneDrive\\java4\\JAVA\\Temp\\rwfile.txt");
try(Writer wr = new FileWriter(rwfile)) {
wr.write("무궁화 꽃이\n".toCharArray());
wr.write("Hello\n");
wr.write("\n");
wr.write("\n");
wr.write("Java");
wr.flush(); //메모리상 작성되었던 내용을 파일로 내림
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
try(Reader rd = new FileReader(rwfile)) {
int data;
while ((data = rd.read()) != -1) {
System.out.print((char) data);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
자바 진도 끝!!