java程序怎样读取linux系统下的文件

如题所述

java是跨平台语言,在linux上读文件跟在windows上读文件是一样的 只是文件路径不一样,可以用File对象和FileInputSteam来读取。但要注意文件编码问题。
如果有中文请做适当的编码转换,通常情况下Linux的默认字符编码为UTF-8编码方式,项目可以直接采用utf8编码方式操作.用System.getProperty("file.encoding")可检查系统编码格式。可改操作系统的文件系统编码,vi /etc/profile,在文件末尾加上
export LANG="zh_CN.GBK"
export LC_ALL="zh_CN.GBK"
编码转换代码:new String(files[i].getName().getBytes("GBK"),"UTF-8");

文件操作的核心代码请参考下面代码:

String path= "/home/";
path= "/home/multiverse/Repository/PMEPGImport";
File file=new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
//FileInputStream fis = new FileInputStream("fileName");

//InputStreamReader isr = new InputStreamReader(fis,"utf-8");
StringBuffer buffer = new StringBuffer();
String text;

BufferedReader input = new BufferedReader (new FileReader(tempList[i]));

while((text = input.readLine()) != null)
buffer.append(text +"/n"); }

if (tempList[i].isDirectory()) {
System.out.println("文件夹:"+tempList[i]);
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-02-18
一般文件路径在windows中用 \ 表示,但是在其他系统平台下比如linux中就不是 \ 所以java给我们提供了一个与平台无关的表示路径的常量 File.separator在windows中则表示 \ 比如现在有一个文件在D:\java\src\myjava中, 如何用绝对路径访问呢?
现在建立一个目录:
File fDir=new File(File.separator); //File.separator表示根目录,比如现在就表示在D盘下。
String strFile="java"+File.separator+"src"+File.separator+"myjava"; //这个就是绝对路径
File f=new File(fDir,strFile); 详细介绍可查看《Linux就该这么学》。