我希望读取多个多行文件并逐个读取文件。并且在每个文件中,我希望将每第三行存储在字符串数组中(即行号 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/