java中怎样从文件中读取数据?

Python010

java中怎样从文件中读取数据?,第1张

分为读字节,读字符两种读法\x0d\x0a◎◎◎FileInputStream 字节输入流读文件◎◎◎\x0d\x0apublic class Maintest {\x0d\x0a\x0d\x0apublic static void main(String[] args) throws IOException {\x0d\x0a\x0d\x0aFile f=new File("G:\\just for fun\\xiangwei.txt")\x0d\x0a\x0d\x0aFileInputStream fin=new FileInputStream(f)\x0d\x0a\x0d\x0abyte[] bs=new byte[1024]\x0d\x0a\x0d\x0aint count=0\x0d\x0awhile((count=fin.read(bs))>0)\x0d\x0a{\x0d\x0a\x0d\x0aString str=new String(bs,0,count)//反复定义新变量:每一次都 重新定义新变量,接收新读取的数据\x0d\x0a\x0d\x0aSystem.out.println(str)//反复输出新变量:每一次都 输出重新定义的新变量\x0d\x0a}\x0d\x0afin.close()\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a◎◎◎FileReader 字符输入流读文件◎◎◎\x0d\x0apublic class Maintest {\x0d\x0apublic static void main(String[] args) throws IOException {\x0d\x0a\x0d\x0aFile f=new File("H:\\just for fun\\xiangwei.txt")\x0d\x0a\x0d\x0aFileReader fre=new FileReader(f)\x0d\x0a\x0d\x0aBufferedReader bre=new BufferedReader(fre)\x0d\x0a\x0d\x0aString str=""\x0d\x0awhile((str=bre.readLine())!=null)//●判断最后一行不存在,为空\x0d\x0a{\x0d\x0aSystem.out.println(str)\x0d\x0a}\x0d\x0abre.close()\x0d\x0a fre.close()\x0d\x0a\x0d\x0a}\x0d\x0a\x0d\x0a}

File 类是对文件和文件夹的抽象,包含了对文件和文件夹的多种属性和操作方法。File类的常用方法如下表:

返回

方法

说明

StringgetName获取文件名称

StringgetParent获取文件的父路径字符串

StringgetPath获取文件的相对路径字符串

StringgetAbsolutePath获取文件的绝对路径字符串

booleanexists判断文件或者文件夹是否存在

booleanisFile判断是不是文件类型

booleanisDirectory判断是不是文件夹类型

booleandelete删除文件或文件夹,如果删除成功返回结果为true

booleanmkdir创建文件夹,创建成功返回true

booleansetReadOnly设置文件或文件夹的只读属性

longlength获取文件的长度

longlastModified获取文件的最后修改时间

String[ ]list获取文件夹中的文件和子文件夹的名称,并存放到字符串数组中