1. 程式人生 > >Java現場寫程式碼的面試題(來試試水啊,本人已跪)

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;
	}
}

測試檔案:

測試結果: