日期:2014-05-20  浏览次数:20812 次

java如何跳过第一行而从第二行开始读?
要读的文件如下,名字叫3.txt。

3
Rajgarh,   Rajasthan
75.38
28.63
Mbini,   Equatorial   Guinea
9.62
1.58
Divo,   Ivory   Coast
-5.37
5.85

第一行表明这个文件中有多少个样本,我要做的是用第一行的数据创建几个对象,然后从第二行开始读入数据,并把数据附给这几个对象。

现在就不知道该怎么样从第二行开始读?各位大侠帮帮忙吧!

------解决方案--------------------

Home > List of Packages > java.io [35 examples] > Reading and Writing [6 examples]

e35. Reading Text from a File

try {
BufferedReader in = new BufferedReader(new FileReader( "C:\\a.txt "));
String str;
int line = 0;
while ((str = in.readLine()) != null) {
line++;
if(line==1) continue;
// process(str);
}
in.close();
} catch (IOException e) {
}

------解决方案--------------------
public class City {
String name;
double latCord;
double longCord;
}
如果我要给3个对象赋值,没法在while循环里做,我需要用一个for循环,像这样

in.readLine(); //多读一行,就完了呗
for(int i=1; i <cityNum+1; i++){
cities[i].name = in.readLine();
cities[i].latCord = Double.parseDouble(in.readLine());
cities[i].longCord = Double.parseDouble(in.readLine());
}


------解决方案--------------------
public class BufferedReaderTest
{
public static void main(String[] args)
{

/**
* 3.txt
* 3
* Rajgarh, Rajasthan
* 75.38
* 28.63
* Mbini, Equatorial Guinea
* 9.62
* 1.58
* Divo, Ivory Coast
* -5.37
* 5.85
*/



try
{
BufferedReader reader = new BufferedReader(new FileReader( "C:\\3.txt "));

String readline = reader.readLine();

int length = Integer.parseInt(readline);
City[] citys = new City[length];
while(length > 0)
{
String name = reader.readLine();
double latCord = Double.parseDouble(reader.readLine());
double longCord = Double.parseDouble(reader.readLine());
citys[citys.length - length] = new City(name, latCord, longCord);
length--;
}
reader.close();

for(City c : citys)
{
System.out.println(c);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
System.err.println( "文件内容缺失!!! ");
}


}
}

class City {
String name;
double latCord;
double longCord;

public City(String name, double latCord, double longCord)
{
this.name = name;
this.latCord = latCord;
this.longCord = longCord;
}

public String toString()
{
return "name= " + name
+ ",latCord= " + latCord
+ ",longCord= " + longCord;