Java现场写代码的面试题(来试试水啊,本人已跪)

1.需求

外部入参(文件路径),参数类型为String,文件内容可能为空,也有很多行,每行中的字段使用冒号分割。

2.要求

现在需要取第行的第二个字段求和数据做统计,要求写一个方法实现需要返回统计的数字。因为是外部传入的文件,所以尽可能写出健壮的方法来实现。

3.自己又写了一遍代码,有错的地方望指正,谢谢 

import java.io.*;

public class FileUtil {
	public static void main(String[] args) {
		//文件路径
		String filePath = "d:/aa.txt";
		Integer countNumber = getCountNumber(filePath);
		System.out.println("统计的数据》》》》:"+countNumber);
	}

	/**
	 * 读取文件并解析文件,统计每行的第二列,返回值用Integer(如果用int 的话无法区分因为int的默认值是0),可以返回null进行区分
	 *
	 * @param filePath
	 * @return
	 */
	public static Integer getCountNumber(String filePath) {
		//1.初始化count
		int count = 0;
		//2.判断文件名是否为空,为空就返回null
		if (filePath == null || "".equals(filePath)) {
			System.out.println("2.判断文件名是否为空,为空就返回null");
			return null;
		}
		//3.读取文件
		File file = new File(filePath);
		//4.文件不存在或者不是文件返回空
		if (file.exists() && file.length() == 0) {
			System.out.println("4.文件不存在或者不是文件返回空");
			return null;
		}
		try {
			//5.读取数据流
			InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "utf-8");
			BufferedReader bufferReader = new BufferedReader(inputStreamReader);
			String lineStr = null;
			try {
				//6.循环每一行
				while ((lineStr = bufferReader.readLine()) != null) {
					//7.通过split转化成数组
					String strs[] = lineStr.split(";");
					if (strs.length < 2) {
						return null;
					}
					try {
						int number = Integer.parseInt(strs[1]);
						count += number;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						System.out.println("file read error!");
						e.printStackTrace();
					}
				}
				//8.关闭
				bufferReader.close();
				inputStreamReader.close();
				return count;
			} catch (IOException e) {

				System.out.println("file read error!");
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {

			System.out.println("file catch unsupported encoding!");
			e.printStackTrace();
		} catch (FileNotFoundException e) {

			System.out.println("file not found!");
			e.printStackTrace();
		}
		return null;
	}
}

测试文件:

测试结果:

猜你喜欢

转载自blog.csdn.net/zhaolinxuan1/article/details/83794955