📌 File 클래스
File.separator
: 해당OS의 경로구분자를 표시해줌경로 리턴하기
🚫 경로만 리턴할 뿐 폴더 혹은 파일을 생성하진 않음
getPath()
: File에 입력된 경로
getAbsolutePath()
: File에 입력된 절대경로타입 확인하기
isDirectory()
: 디렉토리이면 true 반환
isFile()
: 파일이면 true 반환디렉토리 생성하기
mkdir()
: 상위 디렉토리가 없을 경우 생성불가
mkdirs()
: 상위 디렉토리가 없을 경우 상위 디렉토리까지 생성파일 생성하기
creatNewFile()
: 파일 생성내용 입력하기
Stream(스트림)
활용하기
📃 예시01 : 새파일 만들고 내용입력하기
💻 code
File file = new File("src/test/text.txt"); FileWriter writer = null; try{ file.createNewFile(); writer = new FileWriter(file); String str = "안녕하세요"; writer.write(str); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(writer != null) writer.close(); } catch (IOException e) {} }
👉 src/test/text.txt 파일 생성
안녕하세요
🚫 console 출력 아님
📃 예시02 : 파일 복사하기
💻 code
File inFile = new File("src/text.txt"); File outFile = new File("src/copy/text.txt"); FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null;
try { fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); fos = new FileOutputStream(outFile); bos = new BufferedOutputStream(fos); - int input = 0; byte[] buf = new byte[16384]; // 16KB - if(inFile.exists() && inFile.isFile()) { while((input = bis.read(buf)) != -1) { bos.write(buf,0,input); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bos != null) bos.close(); if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } }
👉 src/copy/text.txt 파일 생성 및 복사 완료