从txt文件中读取字符串并将其存储在数组中 [英] reading a string from an txt file and storing it in an array
本文介绍了从txt文件中读取字符串并将其存储在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从char 7开始读取txt文件中的字符串并将其存储在数组中但是这里有一些问题是代码
im trying to read the strings from a txt file starting at char 7 and storing it in an array but am having some issues here is the code
public String[] readNames(String filename)
{
String[] names = new String[5];
String currentLine = "";
int index = 0;
try
{
//make a new scanner object that will read from the file
Scanner in = new Scanner(new File(filename));
//loop as long as the scanner still has contents (use the hasNext method)
while(in.hasNext())
{
//if the current line has "Name" in it, add the name (starts at the
//7th character) to the array and increase the index
if(in.hasNext("name"))
{
names[index] =in.next().charAt(6) ;
index++;
}
//read the next line from the file
currentLine = in.nextLine();
}
推荐答案
public String[] readNames(String filename)
{
String[] names = new String[5];
String currentLine = "", line = "";
int index = 0;
try
{
//make a new scanner object that will read from the file
Scanner in = new Scanner(new File(filename));
//loop as long as the scanner still has contents (use the hasNext method)
while(in.hasNext())
{
//Read the line from file and store it in line variable
line = in.nextLine();
//Check whether line contains name in start
if ( line.startsWith("name"))
{
//Extract string after word "name : " and store it in names array
names[index] = line.substring(7);
index++;
}
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
return names;
}
这篇关于从txt文件中读取字符串并将其存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文