java read text, filter comments, filter spaces, filter blank lines

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();
    }

}

Guess you like

Origin blog.csdn.net/wyyother1/article/details/130268244