Java Basic4(Exception and Java IO)

一、Exception

Error:不可恢复,JVM一些错误

Exception:运行时与非运行时异常,可被捕获,代码本身错误。

不需要程序强制try/catch的都是运行时exception,像各种流,需要强制try/catch,属于非运行时异常。

Finally一定会执行,无论try执行了什么,这样一来,当两者内部都有return时,try中所有都会被忽略,所以尽量不要在finally中出现return。

二、Java IO

1.Java IO简介

2.输入、输出流

3.字节、字符流

4.读取控制台输入

5.缓冲流

6.常见异常

SequenceInputStream,可用于多线程多地址下载;

RandomAccessFile,可用于断点续传;

Java.NIO.*,基于多线程,实现多个管道的操作


ForExample:

CopyFile:

public class CopyFile {

	private static Scanner scanner;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File fileFrom = new File("C:\\Users\\HW91139\\workspace\\JavaTask\\files\\test.txt");
		File fileTo = new File("C:\\Users\\HW91139\\workspace\\JavaTask\\files\\test1.txt");
		
		if (copy(fileFrom, fileTo)){
			System.out.println("输出文件完毕!");
		}else {
			System.out.println("输出文件失败!");
		}

	}
	
	public static boolean copy(File fileFrom, File fileTo){
		FileInputStream in;
		FileOutputStream out;
		if (!fileFrom.exists()) {
			System.out.println("输入文件不存在!");
			return false;
		}
		String judge = "n";
		if (fileTo.exists()) {
			System.out.println("输出文件已存在!是否覆盖?(Y/N)");
			scanner = new Scanner(System.in);
			judge = scanner.nextLine();
		}
		if (!fileTo.exists() || judge.equalsIgnoreCase("y")){
			if (judge.equalsIgnoreCase("y")) {
				System.out.println("覆盖输出文件!");
			}
			try {
				System.out.println("开始输出文件!");
				fileTo.createNewFile();
				in = new java.io.FileInputStream(fileFrom);
				out = new FileOutputStream(fileTo);
				
				byte[] bt = new byte[1024];  
				int count; 
				while ((count = in.read(bt)) > 0) {
					out.write(bt, 0, count);  
				}
				in.close();  
				out.close(); 
				
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}	
			
		}
		return false;		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值