/*
* 输入输出是相对于内存而言的!
* 输入:从硬盘到内存
* 输出:从内存到硬盘
*/
public class TestIO1 {
public static void main(String[] args) throws IOException {
test5();
}
public static void test() throws IOException {
File file = new File("D:\\haha.txt");
boolean newFile = file.createNewFile();
System.out.println(newFile);
}
/*
* 输入:从硬盘到内存
* 一次读取一个字节
*
*/
public static void test1() throws IOException {
FileInputStream fis = new FileInputStream("D:\\haha.txt");
int ch = 0;
//读取到-1结束
while ((ch = fis.read()) != -1) {
System.out.println((char) ch);
}
fis.close();
}
/*
* 一次读取一个字节数组
*
*/
public static void test2() throws IOException {
FileInputStream fis = new FileInputStream("D:\\haha.txt");
int len = 0;
byte[] b = new byte[1024 * 1];
while ((len = fis.read(b)) != -1) {
// 从偏移量0开始读取
String s = new String(b, 0, len);
System.out.println(s);
}
fis.close();
}
/*
* 输出:从内存到硬盘
* 一次写入一个字节
*/
public static void test3() throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\haha.txt");
fos.write(97);
fos.close();
}
/*
* 一次写入一个字节数组
*/
public static void test4() throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\haha.txt");
byte[] b = { 97, 98, 99 };
fos.write(b);
fos.close();
}
/*
* 把字符串转换为字节数组 FileOutputStream fos = new
* FileOutputStream("D:\\haha.txt",true);true 覆盖;false 不覆盖
*/
public static void test5() throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\haha.txt");
String s = new String("hahahahaha");
byte[] b = s.getBytes();
fos.write(b);
fos.close();
}
/*
* 复制一个文件,照片和视频 1 读取原文件的数据 2 创建一个新的文件(omit) 3向新文件写入数据
*/
public static void test6() throws IOException {
FileInputStream fis = new FileInputStream("D:\\IMG_0086.JPG");
FileOutputStream fos = new FileOutputStream("D:\\cpIMG_0086.JPG");
byte[] b = new byte[1024 * 5];
int len = 0;
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
fis.close();
fos.close();
System.out.println("复制完成");
}
}