public class Test1 {
/**
* @param args
* @throws IOException
* 将写出的字节异或上一个数,这个数就是密钥,解密的时候再次异或就可以了
*/
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("copy.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy2.jpg"));
int b;
while((b = bis.read()) != -1) {
bos.write(b ^ 123);
}
bis.close();
bos.close();
}
}
public class Test2 {
/**
* 在控制台录入文件的路径,将文件拷贝到当前项目下
*
* 分析:
*
* 1,定义方法对键盘录入的路径进行判断,如果是文件就返回
* 2,在主方法中接收该文件
* 3,读和写该文件
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File file = getFile(); //获取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName()));
int b;
while((b = bis.read()) != -1) {
bos.write(b);
}
bis.close();
bos.close();
}
/*
* 定义一个方法获取键盘录入的文件路径,并封装成File对象返回
* 1,返回值类型File
* 2,参数列表无
*/
public static File getFile() {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
System.out.println("请输入一个文件的路径:");
while(true) {
String line = sc.nextLine(); //接收键盘录入的路径
File file = new File(line); //封装成File对象,并对其进行判断
if(!file.exists()) {
System.out.println("您录入的文件路径不存在,请重新录入:");
}else if(file.isDirectory()) {
System.out.println("您录入的是文件夹路径,请重新录入:");
}else {
return file;
}
}
}
}
public class Test3 {
/**
* 将键盘录入的数据拷贝到当前项目下的text.txt文件中,键盘录入数据当遇到quit时就退出
*
* 分析:
* 1,创建键盘录入对象
* 2,创建输出流对象,关联text.txt文件
* 3,定义无限循环
* 4,遇到quit退出循环
* 5,如果不quit,就将内容写出
* 6,关闭流
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//1,创建键盘录入对象
Scanner sc = new Scanner(System.in);
//2,创建输出流对象,关联text.txt文件
FileOutputStream fos = new FileOutputStream("text.txt");
System.out.println("请输入数据:");
//3,定义无限循环
while(true) {
String line = sc.nextLine(); //将键盘录入的数据存储在line中
//4,遇到quit退出循环
if("quit".equals(line)) {
break;
}
//5,如果不quit,就将内容写出
fos.write(line.getBytes()); //字符串写出必须转换成字节数组
fos.write("\r\n".getBytes());
}
//6,关闭流
fos.close();
}
}