Android进阶(六)文件读操作
Android中文件的读写操作与Java中文件的读写操作是有区别的。在Java中,读文件操作如以下代码所示:
public class FileRead {
private static final String filePath = "E:/SHQ/workspace/TT/中国火车查询字段对应表.txt";
public static void main(String [] args) throws IOException{
String from_station = "济南";
String to_station = "北京";
readFile(filePath,from_station,to_station);
}
private static String [] readFile(String filepath, String from_station, String to_station) throws IOException{
Map<String, String> map = new HashMap<String, String>();
String s;
String [] data = null;
FileReader fileReader = null;
try {
File inputFile = new File(filepath);
fileReader = new FileReader(inputFile);
BufferedReader bf = new BufferedReader(fileReader);
while ((s = bf.readLine()) != null){
data = s.split(":");
map.put(data[0], data[1]);
}
data[0] = map.get(from_station);
data[1] = map.get(to_station);
System.out.println(data[0] + ">>>>>>>>>>>>>" + data[1]);
return data;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}finally{
fileReader.close();
}
}
}
而在Android开发中则不然!在Android开发中,读文件操作代码如下图所示:
public void search(View source){
// 获取输入的数值时,一定要将获取内容的语句放在按键触发式的方法内
from_station = from_station_name.getText().toString().trim();
to_station = to_station_name.getText().toString().trim();
String res = null;
byte[] buffer = null;
try {
InputStream in = getResources().getAssets().open(fileName);
//返回读取的大概字节数
int length = in.available();
buffer = new byte[length];
in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
res = EncodingUtils.getString(buffer, "GBK");
Map<String, String> map = new HashMap<String, String>();
String[] trainsInfo = null;
String[] medium = null;
//读取火车查询字段对应表(根据调试信息得出)
trainsInfo = res.split("\r\n");
for ( String str: trainsInfo){
medium = str.split(":");
map.put(medium[0], medium[1]);
}
from_station = map.get(from_station);
to_station = map.get(to_station);
url = "https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate="
+ queryDate
+ "&from_station="
+ from_station
+ "&to_station="
+ to_station;
Spider spider = new Spider(this);
spider.execute(url);
}
文章来源: shq5785.blog.csdn.net,作者:No Silver Bullet,版权归原作者所有,如需转载,请联系作者。
原文链接:shq5785.blog.csdn.net/article/details/45220763
- 点赞
- 收藏
- 关注作者
评论(0)