之前也学习过io流,但是时间太长了,所以来复习一下。
1.1文件流
文件是在程序之中是以流的形式来操作的。
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从内存到文件的路径。
.方式一 new File(String pathname)
@Test
public void create01(){
String filepath="D:\\untitled3\\src\\io\\wenjian.txt";
File file = new File(filepath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
方式二 new File(File parent,String child) //父目录文件 +子路径构建
@Test
public void create02() {
File ParentFile = new File("D:\\untitled3\\src\\io");
String fileName="wenjian1.txt";
File file = new File(ParentFile, fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
方式三
@Test
public void create03() throws IOException {
String parentPath="D:\\untitled3\\src\\io";
String fileName="wenjian2.txt";
File file = new File(parentPath, fileName);
file.createNewFile();
System.out.println("文件创建成功");
}
基本多是api的调用,我就快速的看看了。。。
文件的读取
FileInputStream 字节流读取,效率比较低
@Test
public void readFile01() throws IOException {
String filePath="D:\\untitled3\\src\\io\\wenjian.txt";
// 创建fileInputStream对象,用来读取文件
FileInputStream fileInputStream = new FileInputStream(filePath);
int readData=0;
//
while( (readData=fileInputStream.read())!=-1){
System.out.print((char)readData);
}
fileInputStream.close();
}
用字节数组的形式转化为字符串(String)
@Test
public void readFile2() throws IOException {
String FilePath="D:\\untitled3\\src\\io\\wenjian.txt";
int readLenth=0;
byte[] bytes = new byte[8];
FileInputStream fileInputStream = new FileInputStream(FilePath);
while ((readLenth=fileInputStream.read(bytes))!=-1){
System.out.println(new String(bytes,0, readLenth));
}
}
// 可以看看String这个构造器的源码
/* public String(byte bytes[], int offset, int length) {
checkBounds(bytes, offset, length);
// bytes – 要解码为字符的字节
//offset – 要解码的第一个字节的索引
//length - 要解码的字节数
this.value = StringCoding.decode(bytes, offset, length);
}
*/
把内容写入文件
@Test
public void writeFile() throws IOException {
// 创建FileoutputStream
String filepath="D:\\untitled3\\src\\io\\wenjian.txt";
// new FileOutputStream(filepath,true); 追加内容
FileOutputStream fileOutputStream = new FileOutputStream(filepath);
String str="hello world aaaaa";
fileOutputStream.write(str.getBytes()); //字符串转化为字节数组
}