0
点赞
收藏
分享

微信扫一扫

Java IO 流的简单应用,多级目录的文件获取.


 

 

 

 

package pack.java.io.files;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

public class GetFileDemo {
	public static void main(String[] args) {
		String filePath=null;
		try {
			//获得多层文件的方式一:如果文件,不在当前包目录下,则使用getResource("包名和文件名");
			filePath = GetFileDemo.class.getResource("/pack/java/io/test/files/test.txt").toURI().toString();
			//--------------------------------------------------------------------			//获得多层文件的方式二:如果文件,在同一个包的类文件下,则使用getResourceAsStream("文件名"),返回InputStream;
			//InputStream inputStream=GetFileDemo.class.getResourceAsStream("test.txt");
			//--------------------------------------------------------------------
			//这里为什么要使用replace替换函数,是因为,我们用toURI获得文件的路径的时候,把前面"file:/"替换成"";就行了.
			//file:/E:/MyEclipse/HomeWork/IOStreamDemo/WebRoot/WEB-INF/classes/pack/java/io/files/test.txt.
			//如果不替换,则会找不到此路径下面的文件;
			filePath=filePath.replace("file:/","");
			System.out.println(filePath);
		} catch (URISyntaxException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		BufferedInputStream bufferedInputStream = null;
		try {
			bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			FileOutputStream fileOutputStream=new FileOutputStream(new File("C:\\test.txt"));
			int c=0;
			try {
				while ((c=bufferedInputStream.read())!=-1) {
					fileOutputStream.write(c);
				}
				System.out.println("成功写入文件到:"+"C:\\test.txt");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

举报

相关推荐

0 条评论