加载/读取.text文件

时间:2014-12-10 20:25:59

标签: java file filereader

我在Java类简介中的最后一项任务要求我们:

  1. 编写基于控制台(基于AKA命令行)的菜单供您的用户进行交互。
  2. 在菜单中包含以下命令(您必须为每个命令编写代码):
    1. 输入学生列表,使用ArrayDemo中的菜单:显示,添加,删除等。
    2. 使用用户提供的文件名将学生列表保存到文件中
    3. 使用用户提供的文件名从文件中加载学生列表。
  3. 我已经完成了1-3次。如何让程序在.txt文件中加载信息? (老实说,我不确定这是否是我老师在加载时的意思,因为我觉得这可能比我们过去的情况要复杂一些)

    我已经能够让我的程序用记事本打开.txt文件,但我不知道如何让它读取整个文件和/或将文本信息保存到我的程序中。

    import java.util.*;
    import java.util.Scanner;
    import java.io.*;
    
    public class ArrayDemo_File {
        private static Student[]   StudentList = new Student[10];
        private static FileWriter  file;
        private static PrintWriter output;
        private static FileReader fr;
    
        public static void StudentIndex() {
            int index = 0;
    
            while (index < StudentList.length) {
                if(StudentList[index] != null) {
                    System.out.println(index + ": " + StudentList[index].getLName() + ", " 
                        + StudentList[index].getFName());
                }
                else {
                    return;
                }
    
                index++;
            }
        }
    
        // View detailed data for Students listed in the index
        public static void IndexData() {
            int index = 0;
    
            while (index < StudentList.length) {
                if(StudentList[index] !=null) {
                    System.out.println(index + ": " + StudentList[index].getLName() + ", " + StudentList[index].getFName());
                    System.out.println("A Number: \t" + StudentList[index].getANum());
                    System.out.println("Address: \t" + StudentList[index].getAddress());
                    System.out.println();
                }
                else {
                    return;
                }
    
                index++;
            }
        }
    
        // ADD STUDENT
        public static void AddStudent() throws IOException {
            // Memory
            Student student = new Student();
            Address address = new Address();
            Scanner kb = new Scanner(System.in);
    
            String last;
            String frst;
            int num;
    
            int house;
            String Street;
            String City;
            String State;
            int Zip;
            String Line2;
    
            // Student Name and ID
            System.out.println();
            System.out.print("Last Name:\t");
            last = kb.nextLine();
    
            System.out.println();
            System.out.print("First Name:\t");
            frst = kb.nextLine();
    
            System.out.println();
            System.out.print("A Number:\tA");
            num = kb.nextInt();
    
            //Address
            System.out.println();
            System.out.print("What is your house number?\t");
            house = kb.nextInt(); 
            kb.nextLine();
    
            System.out.println();
            System.out.print("What is your Street's name?\t");
            Street = kb.nextLine();
    
            System.out.println();
            System.out.print("What is your city?\t");
            City = kb.nextLine();
    
            System.out.println();
            System.out.print("What is your State?\t");
            State = kb.nextLine();
    
            System.out.println();
            System.out.print("What is your zip code?\t");
            Zip = kb.nextInt();
    
            kb.nextLine();
    
            System.out.println();
            System.out.print("Line 2: \t");
            Line2 = kb.nextLine();
    
            System.out.println("");
    
            // Processing
            address = new Address( house, Street, City, State, Zip, Line2 );
            student = new Student(last, frst, num, address);
    
            int index = 0;
    
            while( index < StudentList.length ) {
                if( StudentList[index] == null ) break;
                index++;
            }
    
            StudentList[index] = student;
        }
    
        // REMOVE STUDENT
        public static void RemoveStudent() {
            System.out.println("Remove student");
    
            int index = 0;
    
            while (index < StudentList.length) {
                if (StudentList[index] !=null) {
                    System.out.println(index + ": " + StudentList[index].getLName() + " " +     StudentList[index].getFName());
                }
                index++;
            }
    
            Scanner kb = new Scanner(System.in);
            int response;
    
            System.out.println(" Please enter student number to remove or -1 to cancel removal");
            System.out.print("\nInput: ");
    
            response = Integer.parseInt(kb.nextLine());
    
            if (response != -1) {
                StudentList[response] = null;
            }
    
            Student[] StudentListTemp = new Student[10];
            int nulls = 0;
            for(int x = 0; x < StudentList.length; x++) {
                if (StudentList[x] == null) {
                    nulls++;
                }
                else {
                    StudentListTemp[x - nulls] = StudentList[x];
                }
            }
    
            StudentList = StudentListTemp;
        }
    
    
        public static void WriteFile() throws IOException {
            String fileName;
            Scanner kb = new Scanner(System.in);
    
            System.out.println("Please enter a  name for your file: ");
            fileName = kb.nextLine();
    
            output = new PrintWriter(fileName + ".txt");
    
            for( int x = 0; x < StudentList.length; x++ ) {
                if( StudentList[x] == null )
                    continue;
    
                output.println( "[" + x + "]" );
                output.println( StudentList[x].getFName()   );
                output.println( StudentList[x].getLName()   );
                output.println( StudentList[x].getAddress() );
            }
    
            output.close();
    
            System.out.println("\n\tFile saved successfully!");
        }
    
        public static void loadFile() throws IOException {
            Student student = new Student();
            String fileName;
            Scanner kb = new Scanner(System.in);
    
            System.out.println("Please enter the name of the file: ");
            fileName = kb.nextLine();
    
            File file = new File(fileName + ".txt");
            if(!file.exists()) {
                System.err.println("\n\tError(404)): File Not Found!");
            }
            else {
                System.out.println("\n\tFile found! It will now open!");
    
                //FileReader fr = new FileReader(fileName + ".txt");
                //System.out.println(fr);
                ProcessBuilder pb = new ProcessBuilder("Notepad.exe", fileName + ".txt");
                pb.start();
            }
        }
    
        //CONSOLE MENU
        public static void Menu() throws IOException {
            Scanner kb = new Scanner(System.in);
            int response;
            boolean run = true;
    
            while(run) {
                System.out.println("--------------------------" );
                System.out.println("  OPTIONS:                 ");
                System.out.println(" 0) View Student Names     ");
                System.out.println(" 1) View Student details   ");
                System.out.println(" 2) Add Student            ");
                System.out.println(" 3) Remove Student         ");
                System.out.println(" 4) Save to File           ");
                System.out.println(" 5) Load File              ");
                System.out.println(" 6) Close Program          ");
                System.out.println("-------------------------- ");
                System.out.print(" Choose an option: ");
    
                response = Integer.parseInt(kb.nextLine());
    
                System.out.println();
    
                switch(response) {
                    case 0:
                        StudentIndex();
                        break;
                    case 1:
                        IndexData();
                        break;
                    case 2:
                        AddStudent();
                        break;
                    case 3:
                        RemoveStudent();
                        break;
                    case 4:
                        WriteFile();
                        break;
                    case 5:
                        loadFile();
                        break;
                    case 6:
                        run = false;
                        break;
                    default:
                        System.out.println(" ERROR: "+ response + " ! ");
                }
            }
    
            System.out.println( "Have a nice day!" );
        }
    
        public static void main(String[] args) throws IOException {
            // StudentList[0] = new Student("Doe", "Jon", 0000, new Address(00, "Road", "City", "State", 37343, "000"));
            // StudentList[1] = new Student("Ricketts", "Caleb", 0001, new Address(000, "000", "000", "0000", 000, "000"));
            // StudentList[2] = new Student("Smith", "Amanda", 2222, new Address(000, "000", "000", "000", 000, "000"));
            // StudentList[3] = new Student("Wilson", "Judy", 3333, new Address(000, "000", "000", "000", 000, "000"));
    
            Menu();
        }
    }
    

    我尝试使用filereader来读取文件,但它没有输出任何内容。不确定我做错了什么。

2 个答案:

答案 0 :(得分:0)

使用这些代码,您可以在SDCard中编写文本文件,同时需要在android manifest中设置权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在写文件之前还要检查你的SD卡是否已安装&amp;您的外部存储状态是可写的

Environment.getExternalStorageState()

鳕鱼:

public void generateNoteOnSD(String sFileName, String sBody){
    try
    {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
    }
    catch(IOException e)
    {
         e.printStackTrace();
         importError = e.getMessage();
         iError();
    }
   }  

Check the http://developer.android.com/guide/topics/data/data-storage.html

答案 1 :(得分:0)

扫描仪可以很好地阅读.txt文件。使用另一个Scanner对象来读取文件,一次一行。代码完成后,文件的每一行都将存储在列表中,每一行都在相应的索引处(例如:list.get(0)将返回第一行,list.get(1)返回第二行等)。

   public static void loadFile()
   {
      Student student = new Student();
      String fileName;
      Scanner kb = new Scanner(System.in);
      Scanner read;
      ArrayList<String> list = new ArrayList<String>();

      System.out.println("Please enter the name of the file: ");
      fileName = kb.nextLine();

      File file = new File(fileName + ".txt");
      if(!file.exists())
      {
         System.err.println("\n\tError(404)): File Not Found!");

      } else {
         System.out.println("\n\tFile found! It will now open!");
         read = new Scanner(file);
         //FileReader fr = new FileReader(fileName + ".txt");
         //System.out.println(fr);
         //ProcessBuilder pb = new ProcessBuilder("Notepad.exe", fileName + ".txt");
         //pb.start();
         while(read.hasNextLine()) {
            String currentLine = read.nextLine();
            list.add(currentLine);
         }
      }

   }