可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。
BufferedReader bre = null
try {
String file = "D:/test/test.txt"
bre = new BufferedReader(new FileReader(file))//此时获取到的bre就是整个文件的缓存流
while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环
{
System.out.println(str)//原样输出读到的内容
};
备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。
package fileimport java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
public class ReadFile {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//将一个已存在文件加载到内存中,读取文本文件
InputStream is = new FileInputStream("xxx.txt")
//获得文件可读取的字节数
int num = is.available()
System.out.println(num)
char[] cs = new char[num]
for (int i = 0i <numi++) {
int num2 = is.read()//ashc码
char c = (char)num2//ashc转换成字符
cs[i]=c
}
String str = new String(cs)
System.out.println(str)
is.close()
}
}
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