我想读取给定的文本文件,并且在文本文件中,它包含 # 字符来分隔山名、国家/地区和海拔。我只想读取除 # 字符之外的所有内容。例如:
A-1 Peak#United States#12377 <-- from the text file
A-1 Peak United States 12377 <-- read in only
我知道我必须使用字符串分割方法,但我不确定我这样做是否正确。
private List<String> readFile(String fileName)
{
List<String> records = new ArrayList<String>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null)
{
String[] parts = line.split("#");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
records.add(line);
}
reader.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return records;
}
最佳答案
使用下面的代码。
while ((line = reader.readLine()) != null){
line = line.replaceAll("#"," ");
records.add(line);
}
关于java - 如何在不读取 # 个字符的情况下读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478573/