티스토리 뷰

프로그래밍/java

Java - 폴더 복사

박스여우 2015. 7. 15. 16:36

 

안녕하세요 박스여우입니다.

이번에는 Java를 이용한 폴더/디렉토리채로 복사하는 방법에대해 알아보겠습니다.

 

 

 

 

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
    
 
    
    public static void copys(File selectFile, File copyFile) { //복사할 디렉토리, 복사될 디렉토리
          File[] ff = selectFile.listFiles();  //복사할 디렉토리안의 폴더와 파일들을 불러옵니다.
          for (File file : ff) {
           File temp = new File(copyFile.getAbsolutePath() +"\\"+ file.getName());

           //temp - 본격적으로 디렉토리 내에서 복사할 폴더,파일들을 순차적으로 선택해 진행합니다. 

           
           if (file.isDirectory()){ //만약 파일이 아니고 디렉토리(폴더)라면
            temp.mkdirs();          //복사될 위치에 똑같이 폴더를 생성하고,
            copys(file, temp);      //폴더의 내부를 다시 살펴봅니다.
           }else{                   //만약 파일이면 복사작업을 진행합니다.
            FileInputStream fis = null;
            FileOutputStream fos = null;
            
            try {
             fis = new FileInputStream(file);
             fos = new FileOutputStream(temp);
             byte[] b = new byte[4096];   //4kbyte단위로 복사를 진행합니다.
             int cnt = 0;
             
             while ((cnt = fis.read(b)) != -1) {  //복사할 파일에서 데이터를 읽고,
              fos.write(b, 0, cnt);               //복사될 위치의 파일에 데이터를 씁니다.
             }
            }catch (Exception e) {
             e.printStackTrace();
            } finally {
             try {
              fis.close();
              fos.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }
           }
          }
         }
cs

 

 

 

아래는 제가 소스를 이용하여 제작한 프로젝트 복사 프로그램입니다.

 

 

 

 

드라이버에 백업하는기능과, 다른 드라이버 ex)USB에 백업하는 기능이 있고,

다중 쓰레드를 통해 여러폴더를 동시에 옮길수 있습니다.

 

 

프로젝트 복사 프로그램의 소스입니다.

메인

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
import java.io.File;
import java.util.Calendar;
 
class backup{
    static gui g;
    static String backup;
    public static void main(String[] args){
        try{
            Calendar calendar2 = Calendar.getInstance();
            int year = calendar2.get(Calendar.YEAR);
            int month = calendar2.get(Calendar.DAY_OF_MONTH);
            int day_week2 = calendar2.get(Calendar.DAY_OF_WEEK);
            int hour2 = calendar2.get(Calendar.HOUR);
            int min2 = calendar2.get(Calendar.MINUTE);
            String test = year+"."+month+"."+day_week2+"."+hour2+"."+min2;
            backup = "D:\\backup\\"+test;
            File f = new File(backup);
            f.mkdir();
        g = new gui(backup);
        g.open();
        backup("File Open!"+backup);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public static void backup(String str){
        g.textArea.append(str+"\r\n");
        System.out.println(str);
    }
    
}
cs

 

gui

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.JButton;
 
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
 
import javax.swing.JLabel;
 
import coping.d_copy;
import coping.usb_copy;
 
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
 
import javax.swing.JTextField;
 
public class gui {
    static String backup;
    gui(String backup){
        this.backup = backup;
    }
    
    public static JTextArea textArea;
    boolean scrollpanemove;
    d_copy copy;
    usb_copy ucopy;
    private JTextField textField;
    
    /**
     * @wbp.parser.entryPoint
     */
    public void open(){
        JFrame main = new JFrame("Box Fox's Project Backup");
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.getContentPane().setLayout(null);
        main.setSize(450350);
        JOptionPane.showMessageDialog(null"사용중인 이클립스를 반드시 종료하고 사용해 주세요!");
        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.addMouseWheelListener(new MouseWheelListener() {
            public void mouseWheelMoved(MouseWheelEvent arg0) {
            scrollpanemove = true;
            }
            });
        
        scrollPane.getVerticalScrollBar().addAdjustmentListener(new 
                AdjustmentListener() {
                @Override
                public void adjustmentValueChanged(AdjustmentEvent arg0) {
                if(scrollpanemove){ //만약 스크롤 무브가 허용되있을시
                scrollpanemove=false//밑으로 내리는 것을 하지않고, 비허용으로 바꾼다.
                }else{
                JScrollBar src = (JScrollBar)arg0.getSource();
                src.setValue(src.getMaximum());
                }
                }
                });
        
        scrollPane.setViewportView(textArea);
        scrollPane.setBounds(1210410215);
        main.getContentPane().add(scrollPane);
        
        JButton btnGui = new JButton("gui");
        btnGui.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                String str = "gui";
                go(str);
            }
        });
        btnGui.setBounds(3192456723);
        main.getContentPane().add(btnGui);
        
        JButton btnClient = new JButton("client");
        btnClient.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                String str = "workspace";
                go(str);
            }
        });
        btnClient.setBounds(822456723);
        main.getContentPane().add(btnClient);
        
        JButton btnServer = new JButton("server");
        btnServer.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                String str = "server";
                go(str);
            }
            });
        btnServer.setBounds(1612456723);
        main.getContentPane().add(btnServer);
        
        JButton btnApp = new JButton("app");
        btnApp.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                String str = "app";
                go(str);
            }
        });
        btnApp.setBounds(2402456723);
        main.getContentPane().add(btnApp);
        
        JButton button = new JButton("client");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String str = "workspace";
                String array = textField.getText();
                sub(array,str);
            }
        });
        button.setBounds(822786723);
        main.getContentPane().add(button);
        
        JButton button_1 = new JButton("server");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String str = "server";
                String array = textField.getText();
                sub(array,str);
            }
        });
        button_1.setBounds(1612786723);
        main.getContentPane().add(button_1);
        
        JButton button_2 = new JButton("app");
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String str = "app";
                String array = textField.getText();
                sub(array,str);
            }
        });
        button_2.setBounds(2402786723);
        main.getContentPane().add(button_2);
        
        JButton button_3 = new JButton("gui");
        button_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String str = "gui";
                String array = textField.getText();
                sub(array,str);
            }
        });
        button_3.setBounds(3192786723);
        main.getContentPane().add(button_3);
        
        JLabel lblNewLabel = new JLabel("drive D:");
        lblNewLabel.setBounds(262454423);
        main.getContentPane().add(lblNewLabel);
        
        JLabel lblUsb = new JLabel("USB");
        lblUsb.setBounds(262784423);
        main.getContentPane().add(lblUsb);
        
        textField = new JTextField();
        textField.setBounds(3912793121);
        main.getContentPane().add(textField);
        textField.setColumns(10);
        
        
        
        main.setVisible(true);
    }
    
    
    public void sub(String array,String str){
        if(array.equals("")) JOptionPane.showMessageDialog(null"경로를 지정해주세요!");
        else{
        File one = new File("C:\\Users\\admin\\"+str);
        File two = new File(array+":\\backup\\"+str);
        textArea.append("Server Project 복사 시작.. \r\n");
        ucopy = new usb_copy(one,two);
        ucopy.start();
        }
    }
    
    public void go(String str){
        File one = new File("C:\\Users\\admin\\"+str);
        File two = new File(backup+"\\"+str);
        textArea.append("Server Project 복사 시작.. \r\n");
        copy = new d_copy(one,two);
        copy.start();
    }
}
 
cs

 

D드라이브 복사 쓰레드

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
import backup.gui;
 
public class d_copy extends Thread{
 
    
    File selectFile, copyFile;
    public d_copy(File selectFile, File copyFile){
        this.selectFile = selectFile;
        this.copyFile = copyFile;
    }
    
 
    public void run() {
          File[] ff = selectFile.listFiles();
          for (File file : ff) {
           File temp = new File(copyFile.getAbsolutePath() +"\\"+ file.getName());
           
           if (file.isDirectory()){
            temp.mkdirs();
            copys(file, temp);
           }else{
            FileInputStream fis = null;
            FileOutputStream fos = null;
            
            try {
            gui.textArea.append(copyFile.getAbsolutePath() +"\\"+ file.getName()+"\r\n");
             fis = new FileInputStream(file);
             fos = new FileOutputStream(temp);
             byte[] b = new byte[4096];
             int cnt = 0;
             
             while ((cnt = fis.read(b)) != -1) {
              fos.write(b, 0, cnt);
             }
             
             gui.textArea.append("complete!\r\n");
            }catch (Exception e) {
             e.printStackTrace();
            } finally {
             try {
              fis.close();
              fos.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }
           }
          }
            gui.textArea.append("Server Project 복사 완료! \r\n");
         }
    
    public static void copys(File selectFile, File copyFile) {
          File[] ff = selectFile.listFiles();
          for (File file : ff) {
           File temp = new File(copyFile.getAbsolutePath() +"\\"+ file.getName());
           
           if (file.isDirectory()){
            temp.mkdirs();
            copys(file, temp);
           }else{
            FileInputStream fis = null;
            FileOutputStream fos = null;
            
            try {
            gui.textArea.append(copyFile.getAbsolutePath() +"\\"+ file.getName()+"\r\n");
             fis = new FileInputStream(file);
             fos = new FileOutputStream(temp);
             byte[] b = new byte[4096];
             int cnt = 0;
             
             while ((cnt = fis.read(b)) != -1) {
              fos.write(b, 0, cnt);
             }
             
             gui.textArea.append("complete!\r\n");
            }catch (Exception e) {
             e.printStackTrace();
            } finally {
             try {
              fis.close();
              fos.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }
           }
          }
         }
    
}
 
 
cs

 

usb 복사 쓰레드

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
import backup.gui;
 
public class usb_copy extends Thread{
 
 
    
    File selectFile, copyFile;
    public usb_copy(File selectFile, File copyFile){
        this.selectFile = selectFile;
        this.copyFile = copyFile;
    }
    
 
    public void run() {
          File[] ff = selectFile.listFiles();
          
          
          for (File file : ff) {
           File temp = new File(copyFile.getAbsolutePath() +"\\"+ file.getName());
           if (file.isDirectory()){
            temp.mkdirs();
            copys(file, temp);
           }else{
            FileInputStream fis = null;
            FileOutputStream fos = null;
            
            try {
            gui.textArea.append(copyFile.getAbsolutePath() +"\\"+ file.getName()+"\r\n");
             fis = new FileInputStream(file);
             fos = new FileOutputStream(temp);
             byte[] b = new byte[4096];
             int cnt = 0;
             
             while ((cnt = fis.read(b)) != -1) {
              fos.write(b, 0, cnt);
             }
             gui.textArea.append("complete!\r\n");
            }catch (Exception e) {
             e.printStackTrace();
            } finally {
             try {
              fis.close();
              fos.close();
             } catch (IOException e) {
              e.printStackTrace();
             }
            }
           }
          }
            gui.textArea.append("Server Project 복사 완료! \r\n");
         }
    
    
    public static void copys(File selectFile, File copyFile) {
          File[] ff = selectFile.listFiles();
          for (File file : ff) {
           File temp = new File(copyFile.getAbsolutePath() +"\\"+ file.getName());
           
           if (file.isDirectory()){
            temp.mkdirs();
            copys(file, temp);
           }else{
            FileInputStream fis = null;
            FileOutputStream fos = null;
            
            try {
            gui.textArea.append(copyFile.getAbsolutePath() +"\\"+ file.getName()+"\r\n");
             fis = new FileInputStream(file);
             fos = new FileOutputStream(temp);
             byte[] b = new byte[4096];
             int cnt = 0;
             
             while ((cnt = fis.read(b)) != -1) {
              fos.write(b, 0, cnt);
             }
             
             gui.textArea.append("complete!\r\n");
            }catch (Exception e) {
             e.printStackTrace();
            } finally {
             try {
              fis.close();
              fos.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }
           }
          }
         }
}
 
 
cs

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
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
글 보관함