一、File
1.File概述
File:文件的意思(文件和文件夹),对计算机来说,文件就是指定盘符下的文件或者文件夹。 构造方法:public File(String pathname) pathname:文件的路径
2.File常用方法
方法: 1.创建文件:public boolean createNewFile() 创建文件,如果文件存在,就不创建,返回false 2.创建文件夹:public boolean mkdir() 创建文件夹,如果文件夹存在,就不创建,返回false,只能创建单个文件夹 mkdir(make directory) 3.创建多层文件夹:public boolean mkdirs() 创建文件夹,如果文件夹存在,就不创建,返回false,可以创建多层文件夹 4.判断是否是文件:public boolean isFile() 5.判断是否是文件夹:public boolean isDirectory() 6.判断文件是否存在:public boolean exists() 7.判断文件的大小:public long length() 返回的是字节个数 结果/1024/1024就是MB 8.获取某个文件夹下面的文件:public String[] list() 返回的是字符串数组,表示的是文件夹下面的文件或者文件夹的名称 windows下的路径分隔符: linux下的路径分隔符符:/
二、流
1.字节输入/输出流
字节输入流:FileInputStrem(读取数据到内存) 字节输出流:FileOutputStrem(写数据到文件 ) 字节输入流
File f= new File ( "xinzhi.txt" ) ;
InputStream in= new FileInputStream ( f) ;
byte [ ] b= new byte [ 1024 ] ;
int count = 0 ;
int temp= 0 ;
while ( ( temp= in. read ( ) ) != ( - 1 ) ) {
b[ count++ ] = ( byte ) temp;
}
in. close ( ) ;
System . out. println ( new String ( b) ) ;
File f = new File ( "xinzhi.txt" ) ;
OutputStream out = new FileOutputStream ( f) ;
String str = "欣知大数据" ;
byte [ ] b = str. getBytes ( ) ;
out. write ( b) ;
out. close ( ) ;
2.字符输入/输出流
字符流的底层还是字节流, 字符流是专门处理文本的 字符输入流: FileReader 字符输出流: FileWriter 字符输入流:
File f = new File ( "xinzhi.txt" ) ;
char [ ] ch = new char [ 100 ] ;
Reader read = new FileReader ( f) ;
int count = read. read ( ch) ;
read. close ( ) ;
System . out. println ( "读入的长度为:" + count) ;
System . out. println ( "内容为" + new String ( ch, 0 , count) ) ;
File f= new File ( "xinzhi.txt" ) ;
Writer out = new FileWriter ( f) ;
String str= "欣知大数据" ;
out. write ( str) ;
out. close ( ) ;
3.字符缓冲输入/输出流
File f = new File ( "xinzhi.txt" ) ;
char [ ] ch = new char [ 100 ] ;
Reader read = new FileReader ( f) ;
BufferedReader bfr= new BufferedReader ( read) ;
int count = bfr. read ( ch) ;
bfr. close ( ) ;
read. close ( ) ;
System . out. println ( "读入的长度为:" + count) ;
System . out. println ( "内容为" + new String ( ch, 0 , count) ) ;
File f= new File ( "xinzhi.txt" ) ;
Writer out = new FileWriter ( f) ;
BufferedWriter bfw = new BufferedWriter ( out) ;
String str= "欣知大数据" ;
bfw. write ( str) ;
bfw. close ( ) ;
out. close ( ) ;