用java如何读取linux中的某个文件

现在系统的日志文件是存放在linux中的,我需要用Java开发一个分析日志的程序,我如何读取到这个文件的内容呢

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个回答  推荐于2017-11-26
import java.io.*;

public class FileToString {
public static String readFile(String fileName) {
String output = "";

File file = new File(fileName);

if(file.exists()){
if(file.isFile()){
try{
BufferedReader input = new BufferedReader (new FileReader(file));
StringBuffer buffer = new StringBuffer();
String text;

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

output = buffer.toString();
}
catch(IOException ioException){
System.err.println("File Error!");

}
}
else if(file.isDirectory()){
String[] dir = file.list();
output += "Directory contents:/n";

for(int i=0; i<dir.length; i++){
output += dir[i] +"/n";
}
}
}
else{
System.err.println("Does not exist!");
}
return output;
}

public static void main (String args[]){
String str = readFile("/home/1.txt");

System.out.print(str);
}
}追问

复制别人代码,不解决问题可耻!

追答

那你就自己解决咯

本回答被网友采纳
第2个回答  2015-07-05
java是跨平台的 在linux上读文件跟在windows上读文件是一样的 只是文件路径不一样而已 可以用FileInputSteam来读取
第3个回答  2015-06-04
和windwos 一样,只不过 文件 的路径 不一样

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网