Skip to content

Instantly share code, notes, and snippets.

@youngjinmo
Created December 25, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youngjinmo/3a30b98558d7281a798aace72af1dc6e to your computer and use it in GitHub Desktop.
Save youngjinmo/3a30b98558d7281a798aace72af1dc6e to your computer and use it in GitHub Desktop.
File 복제하는 클래스
import java.io.*;
public class FileClone {
public static void main(String[] args) throws IOException {
String target = "korean.txt";
String cloneFile = "clone.txt";
// 타겟 대상 파일 읽어들여서 콘솔에 출력하기
String fileread = inputWord(target, 1000);
System.out.println(fileread);
// 파일 읽어들여서 다른이름의 파일 생성하기
createCloneFile(cloneFile, target, 1000);
}
/**
* 파일 읽어들이는 메서드
*
* @param filename
* @param size
* @return
* @throws IOException
*/
static String inputWord(String filename, int size) throws IOException {
File file = new File(filename);
String str = "";
if(file.exists()){
try(BufferedReader reader = new BufferedReader(new FileReader(filename))){
for (int i = 0; i < size; i++) {
String temp = reader.readLine();
if(temp!=null){
str += "\n"+temp;
} else {
break;
}
}
}
return str;
} else {
throw new IOException("파일이 없는데요?");
}
}
/**
* 파일 생성(출력)하는 메서드
*
* @param filename
* @param target
* @param size
* @throws IOException
*/
static void createCloneFile(String filename, String target, int size) throws IOException {
File file = new File(filename);
if(file.exists()){
throw new IOException("같은 이름의 파일이 이미 존재합니다.");
} else {
try(BufferedWriter writer = new BufferedWriter(new FileWriter(filename))){
writer.write(inputWord(target, size));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment