import java.io.RandomAccessFile;
public class readtxt {
// 判断是否读到文件的最后一行数据
public static String getLastLineData(String path, String charset) {
String lastLine = null;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(path, "r");
long lastLinePos = getLastLinePos(raf);
long length = raf.length();
// System.out.println("下标为:"+lastLinePos);
byte[] bytes = new byte[(int) ((length - 1) - lastLinePos)];
raf.read(bytes);
if (charset == null) {
lastLine = new String(bytes);
} else {
lastLine = new String(bytes, charset);
}
} catch (Exception e) {
e.printStackTrace();
}
return lastLine;
}
public static long getLastLinePos(RandomAccessFile raf) {
long lastLinePos = 0;
// 获取文件占用字节数
try {
long len = raf.length();
if (len > 0L) {
// 向前走一个字节
long pos = len - 1;
while (pos > 0) {
pos--;
// 移动指针
raf.seek(pos);
// 判断这个字节是不是回车符
if (raf.readByte() == '\n') {
lastLinePos = pos;// 记录下位置
// break;// 前移到会第一个回车符后结束
return pos;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return lastLinePos;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
RandomAccessFile acf = new RandomAccessFile("D:/log/config.cfg", "r");
String line;
while (null != (line = acf.readLine())) {
System.out.println(new String(line.getBytes("iso-8859-1"),"utf-8"));
String noneSpaceLine = removeAllSpace(line.trim());
if (isAnnotation(noneSpaceLine)) {
continue;
}
String[] txt = noneSpaceLine.split("=");
if (txt[0].equals("key1")) {
System.out.println(txt[1]);
}
if (txt[0].equals("key2")) {
System.out.println(txt[1]);
}
}
acf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 去掉注释
* @param line
* @return
*/
private static boolean isAnnotation(String line) {
if (line.startsWith("#")) {
return true;
}
return false;
}
/**
* 去掉空格
* @param line
* @return
*/
private static String removeAllSpace(String line) {
StringBuilder b = new StringBuilder(line.length());
for (char ch : line.toCharArray()) {
int num = (int) ch;
if (num != 9 && num != 32) {
b.append(ch);
}
}
return b.toString();
}
}
java 读取文本,过滤注释,过滤空格,过滤空行
于 2023-04-20 15:40:26 首次发布
该代码示例展示了如何使用Java的RandomAccessFile类来读取文件的最后一行数据,同时处理不同的字符编码。程序首先找到最后一个回车符的位置,然后读取那之后的字节并转换为字符串。此外,它还包含检查注释和去除空格的功能。
摘要由CSDN通过智能技术生成