[Java] 파일기록&복사 - FileOutputStream&Writer,JFileChooser

package day0225;

 

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.OutputStreamWriter;

 

/**

* 문자열을 파일에 기록

*/

public class UseBufferedWriter {

 

/**

* 8bit+16bit stream 결합

*/

public void useFileOutputStream() {

 

String msg="오늘은 25일 화요일 입니다.";

File file=new File("C:dev/temp/test.txt");

//try~with~resources 사용 : close()가 자동으로 처리된다.

//2.스트림 연결

try(BufferedWriter bw=

new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(file)))){

//3.데이터를 스트림에 기록

bw.write(msg);

//4.스트림의 내용을 목적지로 분출

bw.flush();

System.out.println("파일로에 기록되었습니다. ");

}catch(IOException ie) {

ie.printStackTrace();

}//end catch

 

}//useFileOutputStream

 

/**

*16bit stream 만 사용

*/

public void useBufferedWriter()throws IOException{

String data="내일은 수요일 입니다";

File file=new File("c:/dev/temp/test.txt");

BufferedWriter bw=null;

try {

//스트림 연결

bw=new BufferedWriter(new FileWriter(file));

//스트림에 데이터를 기록

bw.write(data);

//스트림에 내용을 목적지로 분출

System.out.println("스트림에 데이터를 기록");

// bw.flush();

// System.out.println("스트림에 기록된 데이터를 목적지 파일로 분출");

}finally {

if(bw!=null) {bw.close();}

}//end finally

 

 

}//useBufferedWriter

 

public static void main(String[] args) {

UseBufferedWriter ubw=new UseBufferedWriter();

// ubw.useFileOutputStream();

try {

ubw.useBufferedWriter();

} catch (IOException e) {

e.printStackTrace();

}//end catch

}//main

 

}//class

콘솔 출력

스트림에 데이터를 기록

package day0225;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import javax.swing.JOptionPane;

 

public class UseFileOutputStream {

 

public UseFileOutputStream() throws IOException{

//1. 디렉토리를 생성

File dir=new File("C:/dev/temp");

if(!dir.exists()) { //디렉토리가 없으면 생성ㅇ

dir.mkdirs();

}//end if

 

//window 경로 구분 \ , Linux 경로구분 /=> OS에 맞는 구분자 사용

//2. 파일을 만들고

File file=new File(dir.getAbsolutePath()+File.separator+"test.txt");

 

//파일이 없으면 생성하고

//파일이 존재하면 덮어쓸 것인지는 confirmDialog() 사용하여 물어보고

//예가 눌리면 덮어쓰고, 아니오나 취소가 눌리면 덮어쓰지 않는 코드를 작성.

boolean writeFlag=file.exists();

 

if(file.exists()) { //파일이 존재하면?

switch (JOptionPane.showConfirmDialog(

null, file+"이 존재합니다.\n덮어쓰시겠습니까?"))

{

case JOptionPane.OK_OPTION:

writeFlag=false;

break;

}//end switch

}//end if

 

if (writeFlag) {

System.out.println("덮어쓰지 않음");

return;

}//end if

 

FileOutputStream fos=null;

//3. 스트림 연결

try {

fos=new FileOutputStream(file);

int data=65;

//4.스트림에 데이터를 기록

fos.write(data);

//5. 스트림의 기록된 데이터를 목적지로 분출!

fos.flush();//참조형인 경우에만

System.out.println("파일에 기록이 완료되었습니다.");

}finally {

//6. 스트림을 사용했다면 연결을 끊어준다.

//(스트림에 남아있는 데이터가 목적지로 분출되고 연결이 끊어진다.)

if(fos !=null) {

fos.close();}

}//end finally

 

}//UseFileOutputStream

 

public static void main(String[] args) {

try {

new UseFileOutputStream();

} catch (IOException e) {

e.printStackTrace();

}//end catch

 

}//main

}//class

 

package day0225;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

 

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

 

public class FileCopy {

 

public FileCopy() throws IOException {

JFileChooser jfcOpen=new JFileChooser();

jfcOpen.showOpenDialog(null);

 

File file=jfcOpen.getSelectedFile();

 

if (file == null) {

return;

}//end if

 

//복사할 파일명 생성 : 원본파일명_copy.확장자

StringBuilder copyFileName=new StringBuilder(file.getAbsolutePath());

copyFileName.insert(copyFileName.lastIndexOf("."), "_copy");

System.out.println(copyFileName);

 

File copyFile=new File(copyFileName.toString());

 

FileInputStream fis=null;

FileOutputStream fos=null;

 

try {

//파일에서 데이터를 읽기 위한 스트림 연결

fis=new FileInputStream(file); //원본 파일과 연결

 

//파일에서 데이터를 쓰기 위한 스트림 연결

fos=new FileOutputStream(copyFile);

 

// int fileData=0;

// //데이터를 1byte씩 읽어들여 EOF가 아니면

// while( (fileData=fis.read()) != -1) {

// fos.write(fileData); //스트림에 읽어들인 1byte만 기록

// }//end while

// fos.flush(); //스트림에 기록된 내용을 목적지로 분출

 

//HDD의 head 는 한 번에 일반적으로 512byte씩 읽어들임 (제조사 마다 다르긴 함)

byte[] readData=new byte[512];

int readSize=0;

while ( (readSize=fis.read(readData)) != -1) {

//읽어들인 배열의 0번째 방부터 배열의 크기까지를 스트림에 쓴다

fos.write(readData,0,readSize);

// System.out.println("총 " + readSize+"번 읽어들임");

}//end while

fos.flush();

System.out.println("파일복사완료");

} finally {

if(fis != null) { fis.close(); }//end if

if(fos != null) { fis.close(); }//end if

}//end finally

 

}//FileCopy

public static void main(String[] args) {

try {

new FileCopy();

System.out.println("파일 복사 완료");

} catch (IOException e) {

JOptionPane.showMessageDialog(null, "파일 복사 도중 문제 발생");

e.printStackTrace();

}//end catch

 

}//main

}//class

컴파일 시 파일 탐색기가 열리고 이후 진행

package day0225;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import javax.swing.JOptionPane;

 

public class UseFileOutputStream {

 

public UseFileOutputStream() throws IOException{

//1. 디렉토리를 생성

File dir=new File("C:/dev/temp");

if(!dir.exists()) { //디렉토리가 없으면 생성ㅇ

dir.mkdirs();

}//end if

 

//window 경로 구분 \ , Linux 경로구분 /=> OS에 맞는 구분자 사용

//2. 파일을 만들고

File file=new File(dir.getAbsolutePath()+File.separator+"test.txt");

 

//파일이 없으면 생성하고

//파일이 존재하면 덮어쓸 것인지는 confirmDialog() 사용하여 물어보고

//예가 눌리면 덮어쓰고, 아니오나 취소가 눌리면 덮어쓰지 않는 코드를 작성.

boolean writeFlag=file.exists();

 

if(file.exists()) { //파일이 존재하면?

switch (JOptionPane.showConfirmDialog(

null, file+"이 존재합니다.\n덮어쓰시겠습니까?"))

{

case JOptionPane.OK_OPTION:

writeFlag=false;

break;

}//end switch

}//end if

 

if (writeFlag) {

System.out.println("덮어쓰지 않음");

return;

}//end if

 

FileOutputStream fos=null;

//3. 스트림 연결

try {

fos=new FileOutputStream(file);

int data=65;

//4.스트림에 데이터를 기록

fos.write(data);

//5. 스트림의 기록된 데이터를 목적지로 분출!

fos.flush();//참조형인 경우에만

System.out.println("파일에 기록이 완료되었습니다.");

}finally {

//6. 스트림을 사용했다면 연결을 끊어준다.

//(스트림에 남아있는 데이터가 목적지로 분출되고 연결이 끊어진다.)

if(fos !=null) {

fos.close();}

}//end finally

 

}//UseFileOutputStream

 

public static void main(String[] args) {

try {

new UseFileOutputStream();

} catch (IOException e) {

e.printStackTrace();

}//end catch

 

}//main

}//class

 

컴파일 결과

package day0225;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

 

/**

* try~with~resources 사용<br>

* 연결을 제공하는 객체에서 try~with~resources 를 지원하면 자동으로 연결을 끊어준다.

*/

public class UseFileOutputStream2 {

 

public UseFileOutputStream2() {

//1. 디렉토리를 생성

File dir=new File("C:/dev/temp");

if(!dir.exists()) { //디렉토리가 없으면 생성ㅇ

dir.mkdirs();

}//end if

 

//window 경로 구분 \ , Linux 경로구분 /=> OS에 맞는 구분자 사용

//2. 파일을 만들고

File file=new File(dir.getAbsolutePath()+File.separator+"test.txt");

//try~with~resources 를 지원하면 자동으로 연결을 끊어준다.

//3. 스트림 연결

try (FileOutputStream fos=new FileOutputStream(file )) {

//4.스트림에 데이터를 기록

int data=65;

fos.write(data);

//5. 스트림의 기록된 데이터를 목적지로 분출!

fos.flush();//참조형인 경우에만

System.out.println("파일에 기록이 완료되었습니다.");

}catch(IOException ie) {

ie.printStackTrace();

}//end finally

}//UseFileOutputStream2

 

public static void main(String[] args) {

new UseFileOutputStream2();

 

}//main

 

}//class

 

콘솔 출력

파일에 기록이 완료되었습니다.