java按列读取数据再存储_Java指定行读写数据

/**

* 根据指定行写数据

*

* @param lineNumber 要存的行数

* @param data 要存储的数据

*/

public static void setAppointedLineNumber(int lineNumber, String data) throws IOException {

Path path = Paths.get(configuration);

List 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值