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是跨平台语言,在linux上读文件跟在windows上读文件是一样的 只是文件路径不一样,可以用File对象和FileInputSteam来读取。但要注意文件编码问题。\x0d\x0a如果有中文请做适当的编码转换,通常情况下Linux的默认字符编码为UTF-8编码方式,项目可以直接采用utf8编码方式 *** 作.用System.getProperty("file.encoding")可检查系统编码格式。可改 *** 作系统的文件系统编码,vi /etc/profile,在文件末尾加上\x0d\x0aexport LANG="zh_CN.GBK"\x0d\x0aexport LC_ALL="zh_CN.GBK"\x0d\x0a编码转换代码:new String(files[i].getName().getBytes("GBK"),"UTF-8")\x0d\x0a\x0d\x0a文件 *** 作的核心代码请参考下面代码:\x0d\x0a\x0d\x0aString path= "/home/"\x0d\x0apath= "/home/multiverse/Repository/PMEPGImport"\x0d\x0aFile file=new File(path)\x0d\x0aFile[] tempList = file.listFiles()\x0d\x0afor (int i = 0i 回答于 2022-12-11


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

原文地址: https://outofmemory.cn/tougao/11624239.html

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

发表评论

登录后才能评论

评论列表(0条)

保存