对文件输入和输出的操作
获取文件 java.io.File
File类在创建对象的时候(调用构造方法)必须指定文件路径名
写路径名时/必须是//而用\则只要\。
File类只能查询文件的信息,但是不能对文件执行其他写入或读取操作
File类下的方法:
file.exists()判断该路径下的该文件是否存在,返回值为boolean
file.getAbsolutePath()获取该文件的绝对路径
file.isDirectory()判断是否是文件夹还是目录
file.mkdir()创建最后一级目录,返回创建目录是否成功
file.mkdirs()递归创建
file.isFile()返回是否是文件
file.length()返回文件大小,单位是字节
file.list()返回目录下所有的文件列表
file.getName()返回文件名
file.listFiles()获取到目录下的文件列表
IO流分类:输入流和输出流
输入流:字节输入流和字符输入流
字节输入流:FileInputStream
Byte[] b=new Byte[1024];
FileInputStream fis=new FileInputStream(file);
Fis.skip(2);//字节偏移量
Int a=fis.read();//读到最后不能再读,返回附一
While(a!=-1){
a=fis.read(b);//将文件内容输入到b数组中
}
String str =new String(b);//字节字符转成字符串
字节输出流:FileOutputStream
FileOutputStream fos=new FileOutputStream(file,true);//true值为判断是否在原内容上追加内容而不是覆盖
字符输入流:FileReader
字符输出流:FileWriter
FileReader reader=new FileReader(file);
字节转字符
输入流:InputStreamReader
InputStreamReader reader=new InputStreamReader(new FileInputStream(file));//
字符转字节
直接getbyze
如果需要按行读,必须要套用一个缓冲器BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Br.readLine();
注意:流使用完需要关闭
当读取文件是文本文件建议用字符流,
附:文件间复制内容:
public class IOFile {
public static void main(String[] args) {
File file=new File("E://文件.txt");
File file2=new File("E://接受文件.txt");
FileInputStream inputStream=null;
FileOutputStream outputStream=null;
try {
inputStream=new FileInputStream(file);
outputStream=new FileOutputStream(file2);
byte[] buf = new byte[1024];
int b=0;
while((b= inputStream.read(buf))!=-1){
outputStream.write(buf, 0, b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
字节流与字符流的区别在;
传输单位不同:字节流以字节为单位,字符流以两个字节的Unicode为单位