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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java按列读取数据再存储_Java指定行读写数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 域名证书怎么获得(域名证书怎么获得的)
- 下一篇: 怎么dw中导入模板html(dw中模板制