Java指定行读写数据

    /**
     * 根据指定行写数据
     *
     * @param lineNumber 要存的行数
     * @param data       要存储的数据
     */
    public static void setAppointedLineNumber(int lineNumber, String data) throws IOException {
        Path path = Paths.get(configuration);
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        lines.set(lineNumber - 1, data);
        Files.write(path, lines, StandardCharsets.UTF_8);
    }

    /**
     * 1.根据指定行读数据
     *
     * @param lineNumber
     */
    public static String readAppointedLineNumber(int lineNumber) {
        String appointedLine = "";
        FileReader in = null;
        LineNumberReader reader = null;
        try {
            in = new FileReader(configuration);
            reader = new LineNumberReader(in);
            long totalLine = Files.lines(Paths.get(configuration)).count();
            if (lineNumber < 0 || lineNumber > totalLine) {
                throw new Exception("指定行【" + lineNumber + "】不在文件行数范围内");
            }
            int line = 1;
            reader.setLineNumber(lineNumber);
            long i = reader.getLineNumber();
            String s = "";
            while ((s = reader.readLine()) != null) {
                if (i == line) {
                    appointedLine = s;
                    break;
                }
                line++;
            }
            return appointedLine;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(in, reader);
        }
        return appointedLine;
    }

    /**
     * 2.关闭资源
     *
     * @param in
     * @param reader
     */
    public static void closeResource(FileReader in, LineNumberReader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
上一篇:【我的ASM学习进阶之旅】 10 ASM的Core API 的Method的字节码指令的示例讲解


下一篇:Python根据歌曲id爬取网易云音乐歌词