/**
*
*/
package api.io.pratices;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 这个类用来练习测试“文件复制”
*/
public class Test2_FileCopy {
/**
*
*/
public Test2_FileCopy() {
// TODO Auto-generated constructor stub
}
/**
* 日常小黄线:The value of the local variable field is not used;
* 日常小注解:Add @SuppressWarnings 'unused' to main()/method()/field;
* 日常小注解:Add @SuppressWarnings 'deprecation' to main()/method()/field;
* 日常小注解:Add @SuppressWarnings 'resource' to main()/metod()/field;
* 日常小注解:Add @SuppressWarnings 'null' to main()/method()/field;
* 日常小注解:@SuppressWarnings("resource") == @SuppressWarnings({ "resource" })
* 日常小异常:Exception--API(IO)IOException--FileNotFoundException
*/
public static void main(String[] args) {
//字节流In和Out:以字节流读入写出的方式进行不同文件间的资源复制
Test2_FileCopy.method();
}
private static void method() {
/** 文件复制开发思路:
1、创建电脑磁盘文件与程序的数据连接流动通道,实际文件路径名抽象化为抽象路径名
2、字节流读取,将电脑磁盘中的指定文件的数据资源,通过数据连接流动通道,读入程序
3、字节流写入,将程序中从上一个文件读取的数据资源,通过数据连接流动通道,写入与该文件路径相同的另一个文件中,完成文件之间的数据资源复制
4、关闭释放资源 */
//1.2、文件读写,都存在诸多异常,通常直接catch大异常:捕捉处理异常try/catch
try {
//1.1建立程序与电脑磁盘的文件之间的数据连接流动通道is,进行程序与磁盘文件的交互,将磁盘文件的数据读入程序
//普通字节流读入
InputStream is = new FileInputStream(new File("E:\\JavaDevelopmentEngineer\\java\\JDK\\Jdk1.8\\Temps\\Tmooc2002\\Workspaces\\bin\\io\\IONewFile()_2.txt"));
//2.1创建字节写入流工具父类OutputStream实例对象,即建立将程序中存取自上一个文件的数据资源传输到,与上一个文件同意路径下的另一个文件中,的数据连接流动通道
//普通字节写入流,append默认false,默认覆盖该文件中的原有数据
OutputStream os = new FileOutputStream(new File("E:\\JavaDevelopmentEngineer\\java\\JDK\\Jdk1.8\\Temps\\Tmooc2002\\Workspaces\\bin\\io\\IONewFile()_3.txt"));
//1.4通过数据连接流动通道is,将磁盘文件的数据资源读入程序:is.read();
//1.6创建一个变量,记录每读取一次文件数据,得到的字节,直至读完该文件中所有数据资源
int i;
while((i = is.read()) != -1) { //1.5while循环读取文件中所有数据资源到程序中。while循环判断条件:当文件中没有数据资源可读仍读时,返回-1,反之,不等于-1
//1.7将程序从磁盘文件中读到的数据,打印并显示,核查读到的所有数据与文件中的数据是否一致、正确
System.out.print(i);
//2.3通过此写入流通道os,将程序中的数据资源写入文件
// os.write(is.read());
//os.write(i + "");The method write(int) in the type OutputStream is not applicable for the arguments (String)
os.write(i);
}
//1.3程序读取磁盘文件数据资源,通过数据连接流动通道时,应当同时设置水龙头开关,防止数据传输完毕后数据继续在通道中流动传输造成泄露流失
is.close();
//2.2通过数据写入连接流动通道,程序数据读入磁盘文件时,应当同时设置水龙头开关,防止数据传输完毕后数据继续在通道中流动传输造成泄露流失
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
彦舜原创,CSDN首发:文件工具类File,字节流Input/OutStream综合运用,文件间的数据资源复制。未测试,你们看看敲得对吗?
最新推荐文章于 2024-03-05 11:14:36 发布