编程语言
首页 > 编程语言> > Java指定行读写数据

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

标签:Java,String,读写,reader,指定,param,printStackTrace,lineNumber,null
来源: https://blog.csdn.net/sz793919425/article/details/110920319