Java文件拷貝方式

第一種使用FileInputstream讀取,使用FileOutputStream寫入到文件中

		FileInputStream input = null;
		FileOutputStream output = null;
		String path="D:\\java\\";
		String fileName="test.txt";
		String newFilename=System.currentTimeMillis()+".txt";
		try {

			input = new FileInputStream(new File(path+fileName));
			output = new FileOutputStream(new File(path+newFilename));

			byte[] bt = new byte[1024];
			int realbyte = 0;
			while((realbyte=input.read(bt))>0){
			   output.write(bt, 0, realbyte);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	

下面是try-with-resource模式,這種模式中對應類的接口要實現java.lang.AutoCloseable接口或者它的繼承者java.io.Closeable接口,而FileInputStream 對應的抽象類InputStream就實現了java.io.Closeable接口。

		String path="D:\\java\\";
		String fileName="test.txt";
		String newFilename=System.currentTimeMillis()+".txt";
		try
		( FileInputStream input = new FileInputStream(new File(path+fileName));
		  FileOutputStream output = new FileOutputStream(new File(path+newFilename)))
		{ 
			byte[] bt = new byte[1024];
			int realbyte = 0;
			while((realbyte=input.read(bt))>0){
			   output.write(bt, 0, realbyte);
			}			
		}catch (Exception e) {
			e.printStackTrace();
		} 
	
	

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章