欢迎分享,转载请注明来源:内存溢出
分为读字节,读字符两种读法\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}Java中读取txt文件可以使用file类先创建一个对象,然后使用I/O *** 作,进行读取或者写入 *** 作,示例如下:\x0d\x0aimportjava.io.BufferedReader\x0d\x0aimportjava.io.File\x0d\x0aimportjava.io.FileInputStream\x0d\x0aimportjava.io.FileNotFoundException\x0d\x0aimportjava.io.FileOutputStream\x0d\x0aimportjava.io.IOException\x0d\x0aimportjava.io.InputStreamReader\x0d\x0aimportjava.io.PrintWriter\x0d\x0a\x0d\x0apublicclassdemo2{\x0d\x0aprivatestaticStringpath="f:/demo1.txt"\x0d\x0aprivatestaticFilefile\x0d\x0astatic{\x0d\x0afile=newFile(path)\x0d\x0aif(!file.exists()){\x0d\x0atry{\x0d\x0afile.createNewFile()\x0d\x0a}catch(IOExceptione){\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0apublicstaticvoidmain(String[]args)throwsIOException{\x0d\x0aStudentstu=newStudent(1,"张三",90)\x0d\x0awriteDataToFile(file,stu)\x0d\x0areadDataFromFile(file)\x0d\x0a}\x0d\x0a\x0d\x0aprivatestaticvoidreadDataFromFile(Filefile)throwsIOException{\x0d\x0aBufferedReaderreader=newBufferedReader(newInputStreamReader(newFileInputStream(file)))\x0d\x0aStringstr=""\x0d\x0awhile((str=reader.readLine())!=null){\x0d\x0aString[]stuInfo=str.split(",")\x0d\x0aSystem.out.println("学号:"+stuInfo[0]+"姓名:"+stuInfo[1]+"score:"+stuInfo[2])\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0aprivatestaticvoidwriteDataToFile(Filefile,Studentstu)throwsFileNotFoundException{\x0d\x0aPrintWriterout=newPrintWriter(newFileOutputStream(file,true))\x0d\x0aout.println(stu.toString())\x0d\x0aout.close()\x0d\x0a}\x0d\x0a}
赞
(0)
打赏
微信扫一扫
支付宝扫一扫
急求电脑开机出现missing mbr-helper怎么解决
上一篇
2023-04-12
锤子手机自带邮箱推送不及时
下一篇
2023-04-12
评论列表(0条)