Java Java中的空行

时间:2018-07-14 12:36:21

标签: java arraylist

    protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
        List<String> words = new ArrayList<>();
         BufferedReader reader = null;
        try {
             reader = new BufferedReader(new FileReader(srcFile));
            String line;
            while ((line = reader.readLine()) != null) {
                words.add(line);
                System.out.println(line);
            }

            int k = 0;
            for (int i = 0; i < words.size(); i++) {
                k++;
                String[] splitted = words.get(i).split(":");
                String ip = splitted[0];
                String port = splitted[splitted.length - 1];
//                System.out.println(k + " " + ip + " * " + port);
            }
        } catch (IOException iOException) {
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
               ex.printStackTrace();
            }
        }


    }

我想打印输出时没有空行。 这些结果越来越像:

结果1。

结果2。

结果3。

我想要输出:

结果1.
结果2.
结果3。

没有空行。

3 个答案:

答案 0 :(得分:0)

使用System.out.print。请注意,该文件在每一行的末尾包含一个换行符。

如果使用记事本创建了srcFile,请尝试首先删除回车符char System.out.print(line.replaceAll("\\r",""))

答案 1 :(得分:0)

如果字符串为空,则不要将其添加到列表中:

if(!line.trim().isEmpty()) {
    words.add(line);
    System.out.println(line);
}

如果您仍然想将空白行添加到列表中但不显示它们,只需移动条件:

words.add(line);
if(!line.trim().isEmpty())
    System.out.println(line);

Doc

答案 2 :(得分:0)

ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader(srcFile));
    String line;
    while ((line = reader.readLine()) != null) {
        line = line.trim(); // remove leading and trailing whitespace
        if (!line.isEmpty() && !line.equals("")) {

            words.add(line);
            System.out.println(line);
        }
    }