File只是操作文件,并不能操作里面的内容.所以使用流来进行读写操作.
下边是FileInputStream的简单用法
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
// IO,input和Output 输入和输出
// 实现程序和外部的数据交换
// 输入:把外部的数据读取到程序内
// 输出:把程序内的数据返送到外部
// Stream: 流 数据传输方式
// InputStream: 输入流,实现输入操作
// InputStream: 输出流,实现输出操作
// InputStream和InputStream定义了输入输出的方式
// 他们的子类针对某些类型的数据实现更高效的输入输出方式
// 一次读取1字节的数据,
// 参数:
// 1.File对象
// 2.路径,帮我们生成File对象
// 需要捕获异常,处理文件不存在的情况
try {
FileInputStream fis = new FileInputStream("D:/JavaTest/1.txt");
byte[] bytes = new byte[1024];
// 当前这次读取了多少字节的数据
// 读到的数据放入到bytes数组中 一次读1字节
fis.read(bytes);
String text = new String(bytes);
System.out.println(text);
// 流就像水管,用完要关闭
fis.close();
} catch (FileNotFoundException e) {
// 读取数据产生错误
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在使用时要注意冗余的情况
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test2 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D:/JavaTest/1.txt");
// 一次性读取数组长度个字节
byte[] bytes = new byte[5];
int length = 0;
// 通常使用while循环读取全部的数据
while ((length=fis.read(bytes)) != -1) {
// 使用length来避免冗余的产生
String text = new String(bytes, 0, length);
Thread.sleep(100);
System.out.println(text);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileOutputStream向文件内写内容
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test5 {
public static void main(String[] args) {
try {
// 追加写 + true
FileOutputStream fos = new FileOutputStream("D:/JavaTest/2.txt",true);
byte[] bytes = "abcdefg".getBytes();
fos.write(bytes);
// 写第0到length的字节
fos.write(bytes,0,bytes.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
下边写一个将文件夹内的文件复制到一个文件中的例子
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Merge {
public static void main(String[] args) {
File file = new File("D:/JavaTest");
// 先获取文件夹下所有列表
File[] files = file.listFiles();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("D:/123",true);
// 遍历文件夹内的文件
for (File file2 : files) {
// 修改路径
fis = new FileInputStream(file2.getAbsolutePath());
// 赋值内容
byte[] bytes = new byte[(int) file2.length()];
fis.read(bytes);
fos.write(bytes);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}