欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java Basic4(Exception and Java IO),

来源: javaer 分享于  点击 6864 次 点评:94

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;		
	}
}


相关文章

    暂无相关文章
相关栏目:

用户点评