Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //讀取檔案內容
- //https://www.facebook.com/groups/1403852566495675/permalink/2189564644591126/
- //author: Kuo, Hsiang-Yu
- //author: 90ED_7FD4_5B87
- package com.sample;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Scanner;
- public class MainClass {
- public static void main(String[] args) {
- // long t1 = System.nanoTime();
- File file = new File("C:\\Users\\acer\\WorkspaceJava\\讀取檔案內容\\test.txt");
- Scanner scanner = null;
- try {
- scanner = new Scanner(file);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- System.out.println("e = " + e);
- }
- int countLine = 0;
- while (scanner.hasNext()) {
- // 統計這個檔案有幾行字串。
- scanner.nextLine();
- countLine = countLine + 1;
- }
- // System.out.println("countLine = " + countLine);
- try {
- scanner = null;
- scanner = new Scanner(file);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- System.out.println("e = " + e);
- }
- Item[] item = new Item[countLine];// 建一個物件陣列來儲存字串內容。
- String input = "";
- String[] output2 = new String[4];// 設一個陣列,專門儲存切割出來的4個字串。
- int j = 0, k = 0;
- while (scanner.hasNext()) {
- input = scanner.nextLine();
- input = input.trim();// 清除字串前後多餘空白
- // System.out.println(input);
- String[] output = input.split(" ");// 以空格當成切割字元,分割字串。
- j = 0;
- for (int i = 0; i < output.length; i++) {
- if (output[i].equals("") == false) {
- output2[j] = output[i];
- j = j + 1;
- }
- }
- item[k] = new Item(output2[0], output2[1], output2[2], output2[3]);
- k = k + 1;
- }
- // long t2 = System.nanoTime();
- // double seconds = (double) (t2 - t1) / 1000000000.0D;
- // System.out.printf("%f seconds\n", seconds);
- scanner = null;
- scanner = new Scanner(System.in);
- System.out.printf("請輸入檢索資料:");
- input = scanner.next();
- boolean findData = false;
- for (int i = 0; i < item.length; i++) {
- if (item[i].type.equals(input)) {
- item[i].show();
- findData = true;
- }
- }
- if (findData == false) {
- System.out.printf("查無資料。\n");
- }
- scanner.close();
- System.out.printf("\n");
- System.out.println("BUILD SUCCESSFUL (total time: 0 seconds)");
- }
- }
- class Item {
- String id;
- String name;
- String type;
- String year;
- Item(String id, String name, String type, String year) {
- this.id = id;
- this.name = name;
- this.type = type;
- this.year = year;
- }
- void show() {
- // System.out.println(id + " " + name + " " + type + " " + year);
- System.out.printf("%-8s%-7s%-8s%s\n", id, name, type, year);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement