加载/读取.txt文件



我在Java课程入门中的最后一个作业要求我们:

  1. 编写基于控制台(又名基于命令行(的菜单,供用户与之交互。
  2. 在菜单中包括以下命令(必须为每个命令编写代码(:
    1. 输入学生列表,使用 ArrayDemo 中的菜单:显示、添加、删除等。
    2. 使用用户提供的文件名将学生列表保存到文件中
    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("ntFile 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("ntError(404)): File Not Found!");
        }
        else {
            System.out.println("ntFile 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 读取文件,但它没有输出任何内容。不知道我做错了什么。

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

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

在写入文件之前,还要检查您的SDCard是否已挂载以及外部存储状态是否可写

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
扫描仪在

读取.txt文件方面做得很好。 使用另一个 Scanner 对象读取文件,一次读取一行。代码完成后,文件的每一行都会存储在 list 中,每一行在对应的索引处(例如: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("ntError(404)): File Not Found!");
      } else {
         System.out.println("ntFile 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);
         }
      }
   }

最新更新