1. 문자(character) 단위 입출력 스트림 클래스
package com.lec.java.file11;
import java.awt.Frame;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
public class File11Main {
public static void main(String[] args) {
System.out.println("FileReader / FileWriter");
String src = "temp/FileData.txt";
String dst = "temp/FileData.txt";
try(
FileWriter fw = new FileWriter(dst);
FileReader fr = new FileReader(src);
OutputStream out = new FileOutputStream("temp/FileData.bin");
DataOutputStream dout = new DataOutputStream(out);
) {
String str = "안녕하세요";
char [] charArr = {'J', 'A', 'V', 'A'};
fw.write(str);
fw.write(charArr);
fw.flush();
char [] buff = new char[100];
int charsRead = fr.read(buff);
for(int i = 0; i < charsRead; i++) {
System.out.print(buff[i]);
}
System.out.println();
System.out.println("읽은 문자 개수: " + charsRead);
dout.writeChars(str);
for(char ch : charArr) {
dout.writeChar(ch);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("\n프로그램 종료");
}
}
2. 버퍼사용 문자입출력 : BufferedReader, BufferedWriter
package com.lec.java.file12;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class File12Main {
private static final String BIG_TEXT = "temp/big_eng.txt";
public static void main(String[] args) {
System.out.println("FileReader / FileWriter");
try(
FileReader fr = new FileReader(BIG_TEXT);
FileWriter fw = new FileWriter("temp/big_eng_copy1.txt");
FileReader fr2 = new FileReader(BIG_TEXT);
FileWriter fw2 = new FileWriter("temp/big_eng_copy2.txt");
BufferedReader br = new BufferedReader(fr2);
BufferedWriter bw = new BufferedWriter(fw2);
){
System.out.println("FileReader/Writer 만 사용");
int charRead = 0;
int charsCopied = 0;
long startTime = System.currentTimeMillis();
while((charRead = fr.read()) != -1) {
fw.write(charRead);
charsCopied++;
}
fw.flush();
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("읽고 쓴 문자수: " + charsCopied);
System.out.println("경과시간(ms): " + elapsedTime);
System.out.println();
System.out.println("BufferedReader/Writer + 버퍼 사용");
char [] buf = new char[1024];
int charsRead = 0;
charsCopied = 0;
startTime = System.currentTimeMillis();
while((charsRead = br.read(buf)) != -1) {
bw.write(buf, 0, charsRead);
charsCopied += charsRead;
}
fw.flush();
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
System.out.println("읽고 쓴 문자수: " + charsCopied);
System.out.println("경과시간(ms): " + elapsedTime);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("\n프로그램 종료");
}
}
3. PrintWriter / 인코딩
package com.lec.java.file13;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class File13Main {
private static final String FILE1 = "temp/PrintData.txt";
private static final String FILE2 = "temp/PrintData_euckr.txt";
public static void main(String[] args) {
System.out.println("PrintWriter / 인코딩 ");
FileWriter fw = null;
FileReader fr = null;
PrintWriter out = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(FILE1)));
test_write(out);
System.out.println();
br = new BufferedReader(new FileReader(FILE1));
test_read(br);
out.close();
br.close();
System.out.println("현재 인코딩 " + System.getProperty("file.endocing"));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FILE2), "euc-kr")));
test_write(out);
System.out.println();
br = new BufferedReader(new InputStreamReader(new FileInputStream(FILE2), "euc-kr"));
test_read(br);
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
try {
if(br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("\n프로그램 종료");
}
private static void test_read(BufferedReader br) throws IOException {
String line;
StringBuffer sb = new StringBuffer();
while((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb);
}
private static void test_write(PrintWriter out) {
out.println("안녕하세요 Java 한글이 잘 보이나요?");
out.print((2000 + 20) + " " + 3.14);
out.println();
out.printf("%d-%d-%d\n", 2020, 3, 2);
out.flush();
}
}
4. 시스템 정보 확인
package com.lec.java.file14;
public class File14Main {
public static void main(String[] args) {
System.out.println("시스템 정보 확인");
System.out.println();
System.out.println(System.getProperty("os.name"));
System.out.println(System.getProperty("os.arch"));
System.out.println(System.getProperty("os.version"));
System.out.println();
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("java.version"));
System.out.println();
System.out.println(System.getProperty("user.dir"));
System.out.println(System.getProperty("user.home"));
System.out.println();
System.out.println(System.getProperty("file.separator"));
System.out.println("\n프로그램 종료");
}
}
5. 디렉토리 정보 확인
package com.lec.java.file15;
import java.io.File;
public class File15Main {
public static void main(String[] args) {
System.out.println("디렉토리 정보 확인");
System.out.println();
String curWorkingDir = System.getProperty("user.dir");
System.out.println("현재 작업 폴더: " + curWorkingDir);
System.out.println();
File curDir = new File(curWorkingDir);
File [] list = curDir.listFiles();
for (int i = 0; i < list.length; i++) {
if(list[i].isDirectory()) {
System.out.print("DIR" + "\t");
} else {
System.out.print("FILE" + "\t");
}
System.out.print(list[i].getName() + "\t");
System.out.println(list[i].length());
}
System.out.println();
File tempDir = new File("temp");
File[] list2 = tempDir.listFiles();
for(File f : list2) {
if(f.isFile()) {
System.out.print("File\t");
} else {
System.out.println("DIR\t");
}
System.out.println(f.getName() + "\t" + f.length());
}
System.out.println();
String path = "dummy.txt";
File f = new File(path);
System.out.println("파일이름(상대경로): " + f.getName());
System.out.println("절대경로: " + f.getAbsolutePath());
System.out.println("있냐? " + f.exists());
System.out.println("\n프로그램 종료");
}
}
6. 디렉토리 정보 확인
package com.lec.java.file16;
import java.io.File;
import java.io.IOException;
public class File16Main {
public static final String TEST_DIRECTORY = "test";
public static final String TEMP_DIR = "temp";
public static final String TEST_FILE = "dummy.txt";
public static final String TEST_RENAME = "re_dummy.txt";
public static void main(String[] args) {
System.out.println("폴더/파일 생성, 이름변경, 삭제");
System.out.println();
String path = System.getProperty("user.dir")
+ File.separator
+ TEST_DIRECTORY;
System.out.println("절대경로: " + path);
File f = new File(path);
System.out.println();
if(!f.exists()) {
if(f.mkdir()) {
System.out.println("폴더 생성 성공!");
} else {
System.out.println("폴더 생성 실패!");
}
} else {
System.out.println("폴더가 이미 존재합니다.");
}
System.out.println();
File f2 = new File(f, TEST_FILE);
System.out.println(f2.getAbsolutePath());
if(!f2.exists()) {
try {
if(f2.createNewFile()) {
System.out.println("파일 생성 성공!");
} else {
System.out.println("파일 생성 실패!");
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("파일이 이미 존재합니다");
}
System.out.println();
File f3 = new File(f, TEST_RENAME);
System.out.println(f3.getAbsolutePath());
if(f2.exists()) {
if(f2.renameTo(f3)) {
System.out.println("파일 이름 변경 성공!");
} else {
System.out.println("파일 이름 변경 실패!");
}
} else {
System.out.println("변경할 파일이 없습니다");
}
System.out.println();
File f4 = new File(f, TEST_RENAME);
if(f4.exists()) {
if(f4.delete()) {
System.out.println("파일 삭제 성공!");
} else {
System.out.println("파일 삭제 실패!");
}
} else {
System.out.println("삭제할 파일이 없습니다");
}
System.out.println("\n프로그램 종료");
}
}
7. 웹데이터 가져오기(텍스트)
package com.lec.java.file17;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class File17Main {
public static void main(String[] args) {
System.out.println("웹데이터 가져오기(텍스트)");
StringBuffer sb = readFromUrl("https://www.daum.net");
System.out.println(sb);
System.out.println("\n프로그램 종료");
}
public static StringBuffer readFromUrl(String url_address) {
StringBuffer sb = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
InputStream in = null;
InputStreamReader reader = null;
BufferedReader br = null;
char [] buf = new char[512];
try {
url = new URL(url_address);
conn = (HttpURLConnection)url.openConnection();
if(conn != null) {
conn.setConnectTimeout(2000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset-UTF-8");
conn.setUseCaches(false);
System.out.println("request 시작: " + url_address);
conn.connect();
System.out.println("response 완료");
int responseCode = conn.getResponseCode();
System.out.println("responseCode: " + responseCode);
if(responseCode == HttpURLConnection.HTTP_OK) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
int charsRead;
while((charsRead = br.read(buf)) != -1) {
sb.append(buf, 0, charsRead);
}
} else {
System.out.println("response 실패");
return null;
}
} else {
System.out.println("conn fail");
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
if(conn != null) conn.disconnect();
}
return sb;
}
}