1. 程式人生 > >IO操作檔案內容列印到控制檯,將檔案內容複製到另外一個檔案

IO操作檔案內容列印到控制檯,將檔案內容複製到另外一個檔案

package com.yyj.jan.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class FileUtil {
	
	public static void main(String[] args) {
		String url = "D:/CrackCaptcha.log";
		//fileOperate(url);
		File file = new File(url);
		fileCopy(file);
		
		File newfile = new File("d:/rrrr.log");
		newFileCopy(file,newfile);
	}
	/**
	 * 檔案的拷貝
	 * @author yeyuanjin
	 * @data 2017年7月27日
	 * @param url
	 */
	public static void fileOperate(String url){
		File file  = new File(url);
		InputStream in = null;
		try {
			if(!file.exists()){
				file.createNewFile();
			}
			
			in = new FileInputStream(file);
			
			byte[] buff = new byte[1024];
			int length = 0;
			while((length=in.read(buff))!=-1){
				System.out.println(new String(buff,0,length));
			}
		} catch (Exception e) {
			
		}finally{
			try {
				if(in!=null){
					in.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	/**
	 * 檔案的拷貝2
	 * @author yeyuanjin
	 * @data 2017年7月27日
	 * @param file
	 */
	public static void fileCopy(File file){
		String positionUrl = "D:/ddddd.txt";
		//建立檔案輸出目標檔案
		File newFile = new File(positionUrl);
		InputStream in = null;
		OutputStream out = null;
			try {
				if(!newFile.exists()){
					newFile.createNewFile();
				}
				
				int length = 0;
				byte[] buff = new byte[1024];
					in = new FileInputStream(file);
					out = new FileOutputStream(newFile);
					while((length=in.read(buff))!=-1){
						out.write(buff,0,length);
					}
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					if(null!=out){
						out.close();
					}
					if(null!=in){
						in.close();
					}
				} catch (Exception e2) {
					
				}
			}
	}
	
	public static void newFileCopy(File fileIn,File fileOut){
		
		InputStreamReader in = null;
		OutputStreamWriter out  = null;
		
		
		BufferedReader reader = null;
		BufferedWriter writer = null;
		
		try{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileIn),"ISO-8859-1"));
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut),"ISO-8859-1"));
			String line = null;
			while((line=reader.readLine())!=null){
				writer.write(line);
				writer.newLine();
			}
		}catch  (IOException e){
			
		}finally{
			try {
				if(null!=writer){
					writer.close();
				}
				
				if(null!=reader){
					reader.close();
				}
				
				if(null!=out){
					out.close();
				}
				if(null !=in){
					in.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
}