[英]Get Column and Row Size of File Java
我想獲取文件列長度和行長度。
public static void main(String[] args) throws Exception {
InputStream is = GameBoard.class.getClassLoader().getResourceAsStream("level1.txt");
String result = IOUtils.toString(is, StandardCharsets.UTF_8);
System.out.println(result);
}
該文件有 10 列和 10 行。 我現在想將此數字保存在變量中。 但是,我已經用“Apache Commons IO”讀出了該文件,因此在互聯網上找不到太多關於它的信息。 如果有人可以幫助我,我會很高興。
解決方案:
InputStream is = GameBoard.class.getClassLoader().getResourceAsStream("level1.txt");
String result = IOUtils.toString(is, StandardCharsets.UTF_8);
char column;
int totalColumns = 0;
for (int i = 0; i < result.length(); i++) {
column = result.charAt(i);
if (column == '\n') {
totalColumns++;
}
}
int totalRows = 0;
char occ = '\n';
for(int i=0; i < result.length(); i++)
{ if(result.charAt(i) == occ)
totalRows++;
}
System.out.println(totalColumns);
System.out.println(totalRows);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.