我有一个名字的文本文件(最后和第一个)。我已经成功地使用RandomAccessFile类将所有名称加载到字符串数组中。剩下的工作就是将每个名字分配给一个名字数组,将列表中的每个姓氏分配给一个姓氏数组。这是我做的,但我没有得到任何理想的结果。
public static void main(String[] args) {
String fname = "src\\workshop7\\customers.txt";
String s;
String[] Name;
String[] lastName, firstName;
String last, first;
RandomAccessFile f;
try {
f = new RandomAccessFile(fname, "r");
while ((s = f.readLine()) != null) {
Name = s.split("\\s");
System.out.println(Arrays.toString(Name));
for (int i = 0; i < Name.length; i++) {
first = Name[0];
last = Name[1];
System.out.println("last Name: " + last + "First Name: "+ first);
}
}
f.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
请帮帮我,我似乎对使用何种集合以及如何处理感到困惑谢谢
答案 0 :(得分:2)
您可以创建一个方法来读取文件并将数据放入数组中,但是,如果您决定使用数组,则必须以固定大小创建它.b / c数组在java中是不可变的
public class tmp {
public static void main(String[] args) throws FileNotFoundException {
//problem you have to create an array of fixed size
String[] array = new String[4];
readLines(array);
}
public static String[] readLines(String[] lines) throws FileNotFoundException {
//this counter can be printed to check the size of your array
int count = 0; // number of array elements with data
// Create a File class object linked to the name of the file to read
java.io.File myFile = new java.io.File("path/to/file.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(myFile);
/* This while loop reads lines of text into an array. it uses a Scanner class
* boolean function hasNextLine() to see if there another line in the file.
*/
while (infile.hasNextLine()) {
// read a line and put it in an array element
lines[count] = infile.nextLine();
count++; // increment the number of array elements with data
} // end while
infile.close();
return lines;
}
}
但是,首选方法是使用ArrayList
,它是一个在添加数据时使用动态调整大小数组的对象。换句话说,您不必担心具有不同大小的文本文件。
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
String str;
ArrayList<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
BufferedReader和FileInputStream等类使用读取或写入数据的顺序过程。另一方面,RandomAccess与顾名思义完全相同,即允许对文件内容进行非顺序,随机访问。但是,随机访问通常用于其他应用程序,如读取和写入zip文件。除非您有速度问题,否则我建议您使用其他课程。
答案 1 :(得分:1)
public static void main(String[] args) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
String str;
String names[];
List<String> firstName = new ArrayList();
List<String> lastName = new ArrayList();
try {
while ((str = in.readLine()) != null) {
names = str.split("\\s");
int count = 0;
do{
firstName.add(names[count]);
lastName.add(names[count+1]);
count = count + 2;
}while(count < names.length);
}
} catch (IOException e) {
e.printStackTrace();
}
// do whatever with firstName list here
System.out.println(firstName);
// do whatever with LastName list here
System.out.println(lastName);
}