java 读取文本,过滤注释,过滤空格,过滤空行

该代码示例展示了如何使用Java的RandomAccessFile类来读取文件的最后一行数据,同时处理不同的字符编码。程序首先找到最后一个回车符的位置,然后读取那之后的字节并转换为字符串。此外,它还包含检查注释和去除空格的功能。
摘要由CSDN通过智能技术生成
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();
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值