采用命令编译Java 文件的话,下面的代码可以满足楼主的要求。使用字节码.Resource方法。有进行定位。但如果是使用Eclipse编译工具的话,字节码文件是放在bin文件夹下的,所以会造成不在同一个包下的情况。
- package Note;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class Test {
- public static void main(String[] args) {
- // 创建读写流对象
- BufferedOutputStream bos = null;
- BufferedInputStream bis = null;
- String path = Test.class.getResource("\\").toString();
- String oldPath= path.substring(6, path.length()-3)+"Demo.txt";
- String newPath = path.substring(6, path.length() - 3) + "copyDemo.txt";
-
- System.out.println(path);
- System.out.println(newPath);
- System.out.println(oldPath);
- try {
- // 流对象与文件相关联
- bis = new BufferedInputStream(new FileInputStream(oldPath));
- bos = new BufferedOutputStream(new FileOutputStream(
- newPath));
- // 循环判断是否还有数据,不断写入目标文件
- byte[] buf = new byte[1024];
- while ((bis.read(buf)) != -1) {
- bos.write(buf);
- }
- bos.flush();
- } catch (IOException e) {
- e.toString();
- // 关闭资源
- } finally {
- try {
- if (bos != null)
- bos.close();
- System.out.println("写入流已关闭!!!");
- } catch (IOException ex1) {
- ex1.toString();
- }
- try {
- if (bis != null)
- bis.close();
- System.out.println("读取流已关闭!!!");
- } catch (IOException ex2) {
- ex2.toString();
- }
- }
- System.out.println("Copy Over!");
- }
- }
复制代码 |