Java 确保文本文件中的空行未添加到列表中?
我有一个Java 确保文本文件中的空行未添加到列表中?,java,string,list,file,methods,Java,String,List,File,Methods,我有一个Java方法(如下),它检查文本文件中的字符串值,然后将其添加到列表: public List<String> iterateTextFile(String filePath) { List<String> lines = new ArrayList<String>(); try { lines = Files.readLines(new File(filePath), Charset.for
Java方法
(如下),它检查文本文件
中的字符串
值,然后将其添加到列表
:
public List<String> iterateTextFile(String filePath) {
List<String> lines = new ArrayList<String>();
try {
lines = Files.readLines(new File(filePath), Charset.forName("utf-8"));
}catch(IOException e){
e.printStackTrace();
}
return lines;
}
公共列表iteratextfile(字符串文件路径){
列表行=新的ArrayList();
试一试{
lines=Files.readLines(新文件(filePath),Charset.forName(“utf-8”);
}捕获(IOE异常){
e、 printStackTrace();
}
回流线;
}
但是,此方法也会在数组列表中添加空行,例如:”
。我不要这个
如何添加验证以避免出现这种情况?过滤它们:
public List<String> iterateTextFile(String filePath) {
List<String> lines = new ArrayList<String>();
try {
lines = Files.readAllLines(Paths.get(filePath)).stream().filter(str -> !str.trim().isEmpty()).collect(Collectors.toList());
}catch(IOException e){
e.printStackTrace();
}
return lines;
}
公共列表iteratextfile(字符串文件路径){
列表行=新的ArrayList();
试一试{
lines=Files.readAllLines(path.get(filePath)).stream().filter(str->!str.trim().isEmpty()).collect(Collectors.toList());
}捕获(IOE异常){
e、 printStackTrace();
}
回流线;
}
对于预流式java版本,您可以这样做(从最后一个位置转到0,因此不需要重新填充):
公共列表iteratextfile(字符串文件路径){
列表行=新的ArrayList();
试一试{
lines=Files.readLines(新文件(filePath),Charset.forName(“utf-8”);
删除空字符串(列表);
}捕获(IOE异常){
e、 printStackTrace();
}
回流线;
}
私有无效消除mptystring(列表字符串){
对于(int i=strings.size()-1;i>=0;i--){
if(strings.get(i).trim().isEmpty())strings.remove(i);
}
}
注意:添加断言以检查空值,否则可能会出现一些NPE或其他非受控异常。在返回之前,请删除以下空元素:-
for(int i =0; i < lines.size(); i++) {
if(list.get(i).equals("")) {
list.remove(i);
}
}
return list;
for(int i=0;i
看看这个答案:只需修改“LineProcessor”即可过滤掉空行
您也可以尝试以下方法
List<String> lines = new LinkedList<>();
int lineCounter = 0;
Scanner scanner = new Scanner(new File(filePath));
while(scanner.hasNext()){
String currentLine = scanner.nextLine();
lineCounter++;
if(currentLine!=null && currentLine.length()==0){
System.out.println("Skipping empty line number:" + lineCounter);
}else{
lines.add(currentLine);
}
}
List lines=newlinkedlist();
int lineCounter=0;
Scanner Scanner=新扫描仪(新文件(文件路径));
while(scanner.hasNext()){
字符串currentLine=scanner.nextLine();
lineCounter++;
if(currentLine!=null&¤tLine.length()=0){
System.out.println(“跳过空行号:“+lineCounter”);
}否则{
行。添加(当前行);
}
}
请参阅,使用计数器变量指示其是否正常工作。显然,这段代码附带了一个要处理的FileNotFoundException
List<String> lines = new LinkedList<>();
int lineCounter = 0;
Scanner scanner = new Scanner(new File(filePath));
while(scanner.hasNext()){
String currentLine = scanner.nextLine();
lineCounter++;
if(currentLine!=null && currentLine.length()==0){
System.out.println("Skipping empty line number:" + lineCounter);
}else{
lines.add(currentLine);
}
}