Java读取文件并输出到控制台

时间:2014-05-16 00:49:29

标签: java bufferedreader filereader

所以我有一个小问题,由于某些原因我正在消隐,我已经尝试将它移动到循环中并返回到循环外部它不起作用。在返回方法display_names的选项二中,它从文件中读取它们,它将它们写入控制台的一行而不是两行。

例如:

Enter two knew people clicking 3:
smith, rob, 123-123-1234
smith, tom, 123-123-1235
Display names by clicking 2:
smith, rob, 123-123-1234smith, tom, 123-123-1235

instead of:
smith, rob, 123-123-1234
smith, tom, 123-123-1235

主要代码:

import java.util.*;
import java.io.*;

public class ContactList
{

  /**
  Contact list file name 
  */
  private String filename;
  String findMe;



   /**
   ContactList constructor accepts a String parameter
   */
   public ContactList(String inFileName)
   {
      filename = inFileName;
   }

   /**
      3) add a new record to the file. Open the file for writing in append mode(there is a FileWriter constructor with the appropriate parameters).
         a) prompt the user to enter data for each field in the record. Each field is a String.
            The last name is required. If the last name is the empty string(""), return to the menu.
         b) when the user has completed entering data(i.e., all the fields have been prompted), re-display the user choices
         c) do not overwrite existing data
   */
   public void new_record()
   {
    /*
      Prompt for data:
         Last name
         First name
         Phone

    */
  //Create a scanner object
  Scanner scan = new Scanner(System.in); 

  //prompt for the last name
  System.out.println("Last Name: ");

  //input the last name
  String lastName = scan.next();

  //the Last_name must not be empty
   if(lastName.length() > 0)
   {
     //get the first name and the phone
      System.out.println("Enter First Name: ");
      String firstName = scan.next();
      System.out.println("Enter phone number(xxx-xxx-xxxx): ");
      String phone = scan.next();

      //create the output string

      String info = String.format("%s, %s, %s", lastName, firstName, phone);



      //Declare variables to hold file types
      File file = new File(filename);

      //try to open the file for writing - append the data
      try
      {
          if(!file.exists()){
              PrintWriter out = new PrintWriter(filename);
              out.println(info);
              out.flush();
              out.close();
          }
          else if(file.exists()){
             FileWriter fw = new FileWriter(filename, true);
             fw.write(info);
             fw.close();
          }
      }
      catch(IOException ioe)
      {
        System.out.println("new_record: Exception opening the file for writing");
      }

   }//end of test of Last_name

}//end of new_record

/**
2) display all last names and first names in the file. 
Open the file for reading, read each record and 
display the field values.
  a) display all the lastName, firstName paired fields in the file; 
  display with the format lastName, firstName
  b) when all records have been displayed, display the record count  - the record count is the number of records read and should equal the number of records in the file
  c) after all the records and the count have been displayed, display the user choices

*/
public void display_names()
{
  //delare variables to hold file types
  File file = new File(filename);      



  //try to open the file for reading
  try
  {
     if(file.exists()){ //if the file exists allow it to be read
        BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
        String line = br.readLine();
        int count = 0;
        System.out.println("");
        while(line != null){
            System.out.println(line);
            line = br.readLine();
            count++;
        }
        System.out.println("");
        System.out.println("Total records read: " +count);
        br.close();
     }

  }
  catch(IOException ioe)
  {
     System.out.println("display_names: Exception opening the file");
  }

}//end of display_names

    /**
      1) search an address file for a particular last name 
      and then display the Last name, the first name, and 
      the phone for each match
      2) display the count of records which match the last name

   */
public void search(String LastName)
{
  //Declare variables to hold file types
  File file = new File(filename);      
  this.findMe = LastName;

  //try to open the file for reading
  try
  {
     if(file.exists()){ 
         BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
         String s="", line = null;
         int count = 0;
         while((line = br.readLine()) != null){
            String [] parts = line.split(",");
            if(parts[0].equals(findMe)){
                count = 1;
                s= line;
            }
         }
         System.out.println("\n"+s+"\n");
         System.out.println("Total matching records found: " +count);
         br.close();

     }
  }
  catch(IOException ioe)
  {
     System.out.println("search: Exception opening the file");
  }


}//end of search

}//end of class

测试员代码:

import java.util.*;

public class TestContactList
{

   /**
   main
   */
   public static void main(String args [])
   {
      final int ONE = 1;
      final int TWO = 2;
      final int THREE = 3;
      final int FOUR = 4;
      final int FIVE = 5;

      Scanner scan = new Scanner(System.in);

      /*

      */
      while(true)
      {
         System.out.println("1) Search an address file for a particular last name ");
         System.out.println("2) Display all last names and first names in the file ");
         System.out.println("3) Add a new record to the file ");
         System.out.println("4) End the program ");
         System.out.print("Please choose 1 - 4: ");
         int choice = scan.nextInt();
         scan.nextLine();

         /*
         Create a new ContactList object with the name of the
         contact list file.
         */
         ContactList cl = new ContactList("MyAddressBook.txt");

         /*
            if 4 exit program
         */
         if(choice == FOUR)
         {
            System.exit(0);
         }
         /*
            if 1 call search method
         */
         if(choice == ONE)
         {
            System.out.print("Enter name to find: ");
            String findMe = scan.nextLine();

            cl.search(findMe);

         }

         /*
            if 2 call display_names method
         */
         if(choice == TWO)
         {
            cl.display_names();
         }
         /*
            if 3 call new_record method
         */
         if(choice == THREE)
         {
            cl.new_record();
         }

      }//end of while loop

   }//end of main


}

先谢谢xD,我认为这应该是一个简单的修复

2 个答案:

答案 0 :(得分:1)

您的格式字符串(String.format)需要line separator

答案 1 :(得分:1)

好吧,似乎数据文件是这里缺少的:-)但是来自你的代码

while((line = br.readLine()) != null){
  s += line;
  count++;
}
System.out.println("\n"+s+"\n");

您似乎将自己的项目附加到“s”中,并且最终只是在新行之间接受它。

相反,我认为你应该在while循环中添加换行符。

当然,还有其他问题,如使用StringBuilder或StringBuffer来连接字符串。