使用异常处理解决从txt中读取不定长度的数据

来源:互联网 发布:linux netcat渗透 编辑:程序博客网 时间:2024/06/08 14:46

由于没有找到从txt中读取不定长度数据保存到已定长度数组的方法,在调试过程中发现每次使用nextToken()读取完第一行之后就会抛异常,所以决定使用异常处理来完成每行读取完之后就结束当前循环并换行

public static void main(String[] args) {//声明一个100*100的map数组来储存地图int[][] map = new int[100][100];try {FileReader fr = new FileReader("./bin/map/map_001.txt");BufferedReader br = new BufferedReader(fr);br.readLine();StringTokenizer intro;for(int i = 0;i < map.length;i++){intro = new StringTokenizer(br.readLine()," ");try {//使用异常处理来完成每行读取完之后换行for(int j = 0;j < map[i].length;j++){String str = intro.nextToken();if(str != null)map[i][j] = Integer.parseInt(str);if(map[i][j] == 1){System.out.print("#");}else if(map[i][j] == 2){System.out.print("P");}else if(map[i][j] == 3){System.out.print("?");}else if(map[i][j] == 4){System.out.print("S");}else if(map[i][j] == 5){System.out.print(" ");}else{break;}}} catch (Exception e) {System.out.println();}}br.close();} catch (Exception e) {}}

原创粉丝点击