文本abc.txt :
12568 李明
22467 张强里
98654 方芳
22376 何玉宇
...
如何将其写入数组,并进行查询,例如快速将id和姓名对应起来。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*
* <简简单单先这样吧,这种情况是这样的,不支持续写,如果想在后面添加,必须先全部拿出来,在重新存>
* <功能详细描述>
*
* @see [相关类/方法]
*/
public class FileOutPut {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
writeInfo();
readInfo();
}
/**
*
* <读取文件>
* <功能详细描述>
* @throws Exception
* @see [类、类#方法、类#成员]
*/
private static void readInfo() throws Exception{
// TODO Auto-generated method stub
File fList = new File("user.txt");
ObjectInputStream objInput = new ObjectInputStream(
new FileInputStream(fList));
List<User> userList= new ArrayList<User>();
userList = (List<User>) objInput.readObject();
User user = null;
for (int i = 0; i < userList.size(); i++) {简单示例:Scanner in;放入到map中,直接通过get方法获取
try {
in = new Scanner(new FileReader("abc.txt"));
while (in.hasNextLine()) {
int id = in.nextInt();
String name = in.nextLine();
System.out.println(id + " " + name);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
class Reader{
public Map<String, String> getUser(File file){
Map<String, String> users = new LinkedHashMap<String, String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while(true){
String line = reader.readLine();
if(line == null){
break;
}
String[] values = line.split("\\s+");
if(values.length == 2){
users.put(values[0], values[1]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return users;
}
}