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

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}

以下java程序的作用是将当前目录及其子目录中的.java文件袜贺收集到collection.txt文件中,并添加行号,你可告手派以参考一下。

import java.io.*

public class Collection

{

public static void main(String[] args) throws Exception

{

final String F=".\\collection.txt"

FW=new FileWriter(new File(F))

Collection.ProcessDirectory(new File("."))

Collection.FW.flush()

Collection.FW.close()

}

private static void ProcessDirectory(File d) throws Exception

{

File[] ds=null

Collection.ProcessJavaFile(d)

ds=d.listFiles(Collection.DFilter)

for(int i=0i<ds.lengthi++)

{

Collection.ProcessDirectory(ds[i])

}

}

private static void ProcessJavaFile(File d) throws Exception

{

String line=null

LineNumberReader lnr=null

File[] fs=d.listFiles(Collection.FNFilter)

for(int i=0i<fs.lengthi++)

{

lnr=new LineNumberReader(new FileReader(fs[i]))

Collection.FW.write(fs[i].getCanonicalPath()+"\r\n")

System.out.println(fs[i].getCanonicalPath())

while(null!=(line=lnr.readLine()))

{

Collection.FW.write(""+lnr.getLineNumber()+" "+line+"\r\n")

System.out.println(""+lnr.getLineNumber()+" "+line)

}

Collection.FW.write("\r\n")

System.out.println()

}

}

private static FileWriter FW

private static FilenameFilter FNFilter=new FilenameFilter()

{

public boolean accept(File dir,String name)

{

return name.endsWith("薯升.java")

}

}

private static FileFilter DFilter=new FileFilter()

{

public boolean accept(File pathname)

{

return pathname.isDirectory()

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12258307.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存