使用BufferedWriter打开文件

时间:2018-02-21 12:01:55

标签: java filewriter printwriter bufferedwriter

我是Java的初学者;我试图将文本追加到以前使用File类创建并使用PrintWriter写入文件的文本文件。当我在主类中调用第一个方法时,文件被创建并运行。但是,当我调用第二个方法时,调用“try”,但没有新文本添加到.txt文件中。我将第二种方法放入一个单独的公共类中,但我遇到了同样的问题。我是否需要再次初始化fileName变量?

非常感谢。

package project;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.Scanner;
    public class WriteOut {
    private int NumberOfMember;
    private String ProjectName;
    private String[] TeamMember;
    public static String fileName;
    private int[][] Vote;

    public int FirstExport(int NumberOfMember, String ProjectName, String[] TeamMember) {
        Scanner scan = new Scanner(System.in);
        String fileName="ok"; //initializing the file name
        System.out.println("Enter a file name to hold the Project:");
        fileName = scan.nextLine( );
        File fileObject = new File(fileName+".txt");
        while (fileObject.exists( ))
        {
            System.out.println("There already is a file named "
            + fileName);
            System.out.println("Enter a different file name:");
            fileName = scan.nextLine( );
            fileObject = new File(fileName+".txt");
        }
        PrintWriter outputStream = null;
        try
        {
            outputStream =
                 new PrintWriter(new FileOutputStream(fileName+".txt"));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error opening the file " + fileName +".txt");
            System.exit(0);
        }
        for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
        {
            //Statement of variable allocation to corresponding member position
            outputStream.println("Team Member"+(MemberCount)+ ":"+TeamMember[MemberCount - 1]);
        }
        outputStream.println("Number of Members:"+ NumberOfMember+ "\nProject Name:"+ProjectName);
        outputStream.close();

        return NumberOfMember;
        } 
        public int[][] SecondExport(int[][] Vote)  {
            System.out.println("hello"); //test to see if this is being called correctly

            try 
            {
                String content = "This is the content to write into file"; //Test content
                BufferedWriter bw = new BufferedWriter(new FileWriter(fileName+".txt", true));
                bw.append(content);
                System.out.println("Done"); //Test to see if this is being called

                bw.flush();
                bw.close();

            } catch (IOException e) 
            {
                e.printStackTrace();
            }
            return Vote;

        }

    }

我的主类在EnterVotes()方法下调用WriteOut类:

  package project:
    import java.util.Scanner;           //Importing the scanner tool 
import java.util.stream.IntStream; //for summing arrays
import java.io.FileNotFoundException;
import java.text.DecimalFormat;     //Importing the decimal tool

    public class Project
    {
        public static void main(String[] args)
        {
            Project run = new Project();
            run.StartMenu();         
        }

            public static String option; //Declaring the strings representing the menu option buttons
            private static int NumberOfMember;  //Entering the number of members

            public static int index=NumberOfMember; //used for later, declaring a square matrix
            public static String[] TeamMember; //Declaring the strings representing the names of the members
            public static int[][] Vote;

            public static  String ProjectName;  // Declaring the project name variable as a string
            private static boolean CorrectInput, ShowMenu;  //Booleans CorrectInput, which determines whether the user has entered a valid input and ShowMenu, which determines whether the main menu is displayed again
            public String fileName;
            static Scanner scan = new Scanner(System.in);   // Importing the scanner tool
            DecimalFormat twoDecPlcFormatter = new DecimalFormat("0.00");  //Although not used currently, having a decimal formatter could come in handy later
            //----------------------------------------------
            //Declaration of StartMenu(): listing Menu Options and equalsIgnoreCase to accept either upper or lower case
            //----------------------------------------------
                Project(){

                }

                public void StartMenu()             
                {          
                  Scanner scan = new Scanner(System.in);
                  System.out.println();                     
                  System.out.print("\nWelcome to Splitit ");
                  do
                  {
                      printMenu();
                      char input = scan.next().charAt(0);           //Asking user to input a character
                      option = Character.toString(input);           //Converting from characters to string 
                      checkInput(option);                 
                  }
                  while (CorrectInput == false || ShowMenu == true); //Run StartMenu() while either the CorrectInput is false or ShowMenu is true 
                }
                //----------------------------------------------
                //Declaration of checkInput(String OneInput) method
                //----------------------------------------------
                private void checkInput(String OneInput)
                {
                    if (OneInput.equalsIgnoreCase("A") == true)     
                  {
                      About();              
                  }
                    else if (OneInput.equalsIgnoreCase("C") == true) 
                  {
                        CreateProjectTitle();
                  }
                    else if (OneInput.equalsIgnoreCase("V") == true) 
                  {
                      EnterVotes();               
                  }
                    else if (OneInput.equalsIgnoreCase("S") == true) 
                  {
                      ShowProject();              
                  }
                    else if (OneInput.equalsIgnoreCase("Q") == true) 
                  {
                      Quit();
                  }

                    else
                  {
                      System.out.print("\tIncorrect input. "); //If the user has entered an incorrect input, force them to enter in correct input
                      CorrectInput = false;
                  }
                }
                private void printMenu()
                {
                    System.out.println("\n\n\tAbout\t\t(A)");   
                    System.out.println("\tCreate Project\t(C)");
                    System.out.println("\tEnter Votes\t(V)");
                    System.out.println("\tShow Project\t(S)");
                    System.out.println("\tQuit\t\t(Q)");
                    System.out.print("\n\tPlease choose an option: ");   
                }

            //----------------------------------------------
            //Declaration of About() method
            //----------------------------------------------      
                public void About() 
                {
                    System.out.println("\tThis is a program designed to assign grades for a project based on each member's \n \tparticipation. ");                  
                }       

            //----------------------------------------------
            //Declaration of ShowProject()
            //----------------------------------------------    
                public void ShowProject()
                {
                    CorrectInput = true;    
                    ShowMenu = true; 

                    StoreVariables getThings = new StoreVariables();

                    System.out.println("Number of members: " + getThings.getNumberofMember(NumberOfMember)); 
                    System.out.println("Project name: " + getThings.getProjectName(ProjectName));


                    String[] abc = getThings.getTeamMember();
                    for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
                    {
                        System.out.println("Name of member " + Counter + " : " + getTeamMemberName(Counter));
                    }   

                    for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
                    {
                        System.out.println("Votes for Member " + TeamMember[Counter-1] + " : ");
                        System.out.print(getThings.getVotes(Vote));
                    }   

                }

                //----------------------------------------------
                //Declaration of EnterVotes()
                //----------------------------------------------    
                public int[][] EnterVotes()
                {   
                    CorrectInput=true;
                    Vote = new int [NumberOfMember][index];
                    index=NumberOfMember;
                    if (NumberOfMember==0) {
                        System.out.println("Please Create a Project Before Entering Votes!"); //Error Message
                        ShowMenu=true;
                    }

                    for (int row=0; row < Vote.length; row++)
                    {
                        System.out.println("Enter "+ TeamMember[row]+"'s votes, points must add up to 100:");
                        System.out.println();
                        for (int col=0; col < Vote[row].length; col++)
                        { 
                            System.out.println("Enter "+TeamMember[row]+ "'s points for"+ TeamMember[col]+":");
                            Vote[row][col] = scan.nextInt(); 
                        }
                    }

                    //if (sum!=100){
                        //System.out.println("Error. Please make sure all votes add up to 100.");
                        //EnterVotes();
                    //}
                   sumRow(Vote, NumberOfMember);
                   return Vote;
                }
                public int[] sumRow(int[][] Vote, int NumberOfMember) 
                {
                     int sum[] = new int[NumberOfMember];

                        for (int i = 0; i < Vote.length; i++){
                        int total = 0;
                        for (int j = 0; j < Vote[0].length; j++)
                        total +=Vote[i][j];
                        sum[i] = total;}


                        for(int i = 1; i < sum.length; i++)
                        {
                          if (sum[i] != 100) {
                              System.out.println("Please Make Sure the points add to 100!");
                              EnterVotes();
                          }
                        }
                        WriteOut getsecond = new WriteOut();
                        getsecond.SecondExport(Vote);
                        return sum;
                        }





                //----------------------------------------------
                //Declaration of CreateProject()
                //----------------------------------------------    

                public String CreateProjectTitle()
                {  

                    CorrectInput = true;                                        
                    ShowMenu = true;                                            //Still show Menu
                    System.out.print("\n\tEnter the project name: ");           //Asking user for a project name
                    ProjectName = scan.next();
                    CreateProjectNumberofMembers(); //calling methods within the resulting methods
                    CreateProjectNamesofMembers();
                    return ProjectName;
                    }

                public int CreateProjectNumberofMembers(){ //ENTER NUMBER OF TEAM MEMBERS
                    System.out.print("\tEnter the number of team members: ");   //Asking user to input a number for all members count
                    NumberOfMember = scan.nextInt();
                    System.out.print("\n");
                    return NumberOfMember;          
                }

                public String[] CreateProjectNamesofMembers(){ 
                    TeamMember = new String[NumberOfMember];

                    for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
                    {
                        //Statement of variable allocation to corresponding member position
                        System.out.print("\tEnter the name of team member " + MemberCount + ": ");
                        TeamMember[MemberCount - 1] = scan.next();

                    }

                    WriteOut getThings2= new WriteOut();
                    getThings2.FirstExport(NumberOfMember, ProjectName, TeamMember);
                    System.out.print("Press any key to return to the main menu: ");
                    String DummyInput = scan.next();    //This is a dummy variable where the input is never used again
                    ShowMenu = true;                    //Irrespective of the input, the menu will be shown again by assigning this boolean to tr 


                    return TeamMember;

                }

                //----------------------------------------------
                //Declaration of Quit() method
                //----------------------------------------------    
                public void Quit()
                {
                    CorrectInput = true;                
                    ShowMenu = false;                   //if ShowMenu is false, the program's menu will terminate
                    //WriteOut();
                    System.out.println("\tGoodbye. ");      
                    scan.close();
                }


                //--------------------------------------------------------------------------------
                //Declaration of toString() method to check for all variable values when necessary
                //--------------------------------------------------------------------------------  
                private String getNumberOfMember()
                {
                    return Integer.toString(NumberOfMember);
                }
                private String getProjectName(int NumberOfProjects)
                {
                    return ProjectName;
                }

                private String getTeamMemberName(int index)
                {
                    return TeamMember[index - 1];
                }

        }

2 个答案:

答案 0 :(得分:0)

class WriteOut中有一个字段:

public static String fileName;

然后在FirstExport中使用相同名称的局部变量:

String fileName="ok"; //initializing the file name

局部变量优先于FirstExport,当你进入SecondExport时,该字段为空。如果你只是删除局部变量声明,你将得到我理解的预期行为。

答案 1 :(得分:0)

删除方法FirstExport中的局部变量:

String fileName="ok";

您只想使用公共字段

public static String fileName;

所以你可以从这两种方法中访问它。