好像经常看到有面试题分享把文件从某盘拷到某盘,不知道是不是字符流这个- -。
总之,稳扎稳打,步步为营~!
- /**
- *
- */
- package day18_IOStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- /**
- * @author always
- *
- */
- public class CopyTest {
- /**
- * 将C盘一个文件复制到D盘
- */
- public static void main(String[] args) throws IOException{
- // TODO Auto-generated method stub
- // copyFileByChar();
- copyFileByBuffer();
- }
- public static void copyFileByChar() {
-
- FileWriter fw = null;
-
- FileReader fr = null;
-
- try {
- /*创建目的地*/
- fw = new FileWriter("d:\\CopyFile.txt");
- /*与已有文件关联*/
- fr = new FileReader("C:\\Intel\\Logs\\IntelGFX.log");
- int ch = 0;
- while((ch = fr.read()) != -1) {
- fw.write(ch);
- }
- } catch(IOException e) {
- throw new RuntimeException("读写失败");
- }
-
- /*关闭流资源*/
- finally {
- if(fw != null)
- try {
- fw.close();
- } catch(IOException e) {
- System.out.println(e);
- }
- if(fr != null)
- try{
- fr.close();
- } catch(IOException e) {
- System.out.println(e);
- }
- }
- }
- public static void copyFileByBuffer() throws IOException{
- /*创建待写入目标文件,如果文件已存在,则续写*/
- FileWriter fw = new FileWriter("d:\\CopyFile.txt",true);
-
- /*创建读取流对象,与待读取文件关联*/
- FileReader fr = new FileReader("C:\\Intel\\Logs\\IntelGFX.log");
-
- char[] buf = new char[1024];
- int len = 0;
-
- /*通过把字符读取到数组把字符写入到.txt文件*/
- while((len = fr.read(buf)) != -1) {
- fw.write(buf, 0, len);
- }
-
- /*关闭流资源*/
- fr.close();
- fw.close();
- }
- }
复制代码 |
|