java - 读取文件时需要相应地跳过行号(了解更多)

标签 java string jsp bufferedreader

我希望读取多个多行文件并逐个读取文件。并且在每个文件中,我希望将每第三行存储在字符串数组中(即行号 1,4,7,10,.... 等必须存储在字符串数组中)我尝试了此代码,但它仍然将所有三个文件的每一行保存在数组中。但我想跳过两行并在数组中添加每第三行。 帮帮我吧。

这是代码

import java.io.*;
import java.util.*;

public class music {
public double xx[] = new double[5];
public String songs[] = new String[40000];
//public static File f = new File("C:/Users/Prashant/Desktop/OCEAN/f.txt");
public static File[] fileList1 = new File("C:/Users/Prashant/Desktop/MUSIC/Categories").listFiles();

public void selectsongs() throws IOException, FileNotFoundException, ArrayIndexOutOfBoundsException //, NoSuchElementException
{
    int i;
    int lineno = 1;
    int songno = 0;
    String t = "";
    xx[0]=51;
    xx[1]=10;
    xx[2]=60;
    xx[3]=60;
    xx[4]=60;

    if (xx[0] >= 50 && xx[1] < 50 && xx[2] >= 50 && xx[3] >= 50 && xx[4] >= 50) {
        for (i = 0; i < 3; i++) {
            Scanner scanner1 = new Scanner(fileList1[i]);
            lineno = 1;
            while (scanner1.hasNextLine()) {
                t = "";
                if (lineno % 3 == 1) {
                    t = t + scanner1.nextLine();
                    songs[songno] = t;
                    songno++;
                }
                lineno++;
            }
        }
    }
    for(int j=0;j<songno;j++)
    {
        System.out.println(songs[j]);
    }
}
public static void main(String args[])
{

}
}

最佳答案

如果您调用nextLine扫描仪只会前进一行。 hasNextLine 不影响状态。因此,您必须在 while 循环的每次迭代中调用 nextLine,但仅在适当的时候将返回值放入数组中。

关于java - 读取文件时需要相应地跳过行号(了解更多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535283/

相关文章:

java - 最新的 appengine-gcs-client lib 产生 GCS Java API 弃用警告

在C中复制字符串的结尾

python - 字符串的绘图函数在 0 时无法正确计算

ruby-on-rails - 避免使用#encoding : UTF-8

java - 排序 HashMap

java - 如何使用 JavaEE eclipse 将我的 React Native 应用程序连接到 MySQL 数据库?

java - oracle.jdbc.ReadTimeout 与 Connection.getNetworkTimeout 与 Statement.setQueryTimeout

jquery - 我使用jsp将数据存储在session中。如何使用 jquery 检索数据?

java - 初学者构建 jsp 的指导

java - 当我重定向到 Struts 1.3 应用程序中的登录页面时如何显示 ":Invalid username and password"