当前位置:网站首页>Handling file exceptions

Handling file exceptions

2022-07-07 23:07:00 Anny Linlin

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.imageio.stream.FileImageInputStream;

import org.omg.CORBA_2_3.portable.InputStream;

/*
 *  Copy java file , exception handling 
 */
public class CopyWenjian {

	public static void main(String[] args) {
		
		OutputStreamWriter osw = null;
		InputStreamReader isr = null;

		try{

			osw = new OutputStreamWriter(
					new FileOutputStream("E:\\EclipseCode\\file\\src\\fos.txt"));
			
			isr = new InputStreamReader(
					new FileInputStream("E:\\EclipseCode\\file\\fos.txt"));
			
			int len;
			char [] chs = new char[1024];
			while((len=isr.read(chs))!=-1){
				osw.write(chs);
			}

		}catch(Exception e){
			e.printStackTrace();
		}finally {

			try{
				if(isr!=null){
					isr.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}

			try{
				osw.close();
			}catch(Exception e){
				e.printStackTrace();
			}

		}
		
	}

}

The above code is JDK5 How to handle file exceptions before .

public static void main(String[] args) {
		try(OutputStreamWriter osw = new OutputStreamWriter(
				new FileOutputStream("E:\\EclipseCode\\file\\src\\fos.txt"));
		
		InputStreamReader isr = new InputStreamReader(
				new FileInputStream("E:\\EclipseCode\\file\\fos.txt"));)
		{
			int len;
			char [] chs = new char[1024];
			while((len=isr.read(chs))!=-1){
				osw.write(chs);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

Above is JDK7 Exception handling scheme for .

private static void copyTxt() throws IOException{
		OutputStreamWriter osw = new OutputStreamWriter(
				new FileOutputStream("fos.txt"));
		
		InputStreamReader isr = new InputStreamReader(
				new FileInputStream("fisr.txt"));
		try(osw;isr){
			int len;
			char [] chs = new char[1024];
			while((len=isr.read(chs))!=-1){
				osw.write(chs);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

Above is JDK7 The following scheme for handling file exceptions .

原网站

版权声明
本文为[Anny Linlin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130601098259.html