자바/자바 기본
자바 JAVA FILE COPY 파일 복사/수정 간단 예제
은은하게미친자
2022. 6. 17. 15:31
728x90
* 파일 복사 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package kr.co.obj;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import javax.xml.crypto.Data;
public class FileTest2 {
public static void main(String[] args) throws FileNotFoundException, IOException {
//=file 열어서 복사하기=============================================
String rfilename = "tomboy.abc";
String wfilename = "output.txt";
FileReader fr = null; //주스트림.
BufferedReader br = null; //보조스트림
FileWriter writer = null;
fr = new FileReader(rfilename);
br = new BufferedReader(fr); //생성자 안에 new해서 쓰는거 - 익명 클래스 일회적으로 사용하고 버려짐.
writer = new FileWriter(wfilename);
while(true) {
int read = br.read(); // 읽을때 문자타입 , 바이트타입도 있움.
if (read==-1) // -1 if the end of the stream has been reached
break;
char c = (char)read;
System.out.print(c);
writer.write(c);
}
br.close(); //FIANLLY에 쓰면 조움
writer.close(); //꼭 닫아줘야 파일 쓰기가 마무리됨! //FIANLLY에 쓰면 조움
//=Files.copy 방식=============================================
String filename = "tomboy.abcd";
String filename1 = "tomboy.abcde";
File orgfile = new File(rfilename);
File copyfile = new File(filename);
//=Files.copy 방식=============================================
Files.copy(orgfile.toPath(), copyfile.toPath());
copyfile = new File(filename1);
//=Files.copy 방식===Replace an existing file if it exists.
Files.copy(orgfile.toPath(), copyfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
|
cs |
* 파일 수정 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package kr.co.obj;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileTest3 {
public static void main(String[] args) throws FileNotFoundException,IOException{
/*
* 파일을 쓸때 재 생성 되는것이 아니라
* 문서뒤에 추가하여 사용하는 방법
* new FileWriter(wname, true);
* true가 붙으면 추가가능함 */
boolean stop = false;
Scanner scan = new Scanner(System.in);
String wname = "output.txt";
FileWriter writer = new FileWriter(wname, true);
// FileWriter 생성자 2번째 인자에 true를 넣으면 기존파일에 txt추가
// false 일경우 기존 파일 삭제되고 처음 부터 입력.
while(!stop) {
System.out.println("아무 문자열이나 입력(종료는 00 입력)");
String str = scan.nextLine();
if(str.equals("00")) {
stop = true;
break;
}
writer.write("\n"+str);
}
writer.close();
}
}
|
cs |
728x90