Java Java中的空行

 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。


没有空白行。


SMILET
浏览 225回答 3
3回答

呼唤远方

如果字符串为空,则不要将其添加到列表中:if(!line.trim().isEmpty()) {&nbsp; &nbsp; words.add(line);&nbsp; &nbsp; System.out.println(line);}如果您仍想将空白行添加到列表中但不显示它们,则只需移动条件:words.add(line);if(!line.trim().isEmpty())&nbsp; &nbsp; System.out.println(line);

汪汪一只猫

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

慕神8447489

使用System.out.print。请注意,该文件在每一行的末尾包含一个换行符。如果使用记事本创建了srcFile,请尝试首先删除回车符char&nbsp;System.out.print(line.replaceAll("\\r",""))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java