如何将控制台输出写入用户命名文件

时间:2015-01-30 02:20:04

标签: java console output

我的问题很简单。我相信解决方案也很简单。但我的尝试失败了。我查看了与此相关的每个问题,但它不包含我正在寻找的解决方案。我正在使用我的类VideoGameManager中的ReadGameFile()方法和WriteToGameFile()方法。我有一个类,其中包含一个以下列方式输出数据的方法: 这个类叫做VideoGameManager 其中有一个名为public void printSearchCriteria的方法(String nameInput,String consoleInput);

名称(标签空间)平台

name" "平台

name" "平台

....等。

然后在主类我有一个VideoGameManaer的新实例

VideoGameManager vG = new VideoGameManager();

然后我调用使用以下参数输出数据的方法

用户输入

nameInput = keyboard.next();

consoleInput = keyboard.next();

vG.printSearchCriteria(String nameInput,String consoleInput);

这导致数据以上述方式打印。 我现在需要找到一种方法来获取该输出。并将其存储在用户将命名的新文件中。

System.out.println("输入要打印的文件名。");

String fileNamePrintToFile = keyboard.next();

//从printSearchCriteria的输出中获取数据并将其存储在用户输入-fileNamePrintToFile的新文件中的某种方式。

VideoGameManager文件

public class VideoGameManager {
Scanner keyboard = new Scanner(System.in);
//array list
private ArrayList<VideoGame> games; 
//tab
private static final String delim = "\t";

//constructor
public VideoGameManager(){
    games = new ArrayList<VideoGame>();
}


public void ReadGameFile(String fileName)
{
    //This reconstructs a new instance of the VideGame array list.
    //This is done to clear the array list
    games = new ArrayList<VideoGame>();
    try
    {
        //Create a new file Scanner
        Scanner fileScanner = new Scanner(new File(fileName));
        //Reads each line in the file one-by-one
        while(fileScanner.hasNextLine())
        {
            //Stores the next line of code
            String nextLine = fileScanner.nextLine();
            //That line is then split using the delimiter (\t)
            String[] splitStrings = nextLine.split(delim);
            //If the newly created array is not 2 items in length then
            //that line is not correctly formatted and should be ignored.
            if(splitStrings.length != 2)
                continue;
            String gameName = splitStrings[0];//The first element is the game name
            String console = splitStrings[1];//Next is the console
            VideoGame newVideoGame = new VideoGame(gameName,console); 
            games.add(newVideoGame);//Added to the array list
        }
        fileScanner.close();
    }
    catch(Exception e)
    {
        System.out.println(" File does not exist ");
    }

}
public void WriteToGameFile(String fileName, boolean append)
{
    if(games == null)//if the file name is null then return
        return;
    try
    {
        //Creates the new instance of a print writer
        PrintWriter fileWriter = new PrintWriter(new FileOutputStream(fileName,append));
        for(VideoGame aVideoGame : games)
        {
            //Prints to the file
            fileWriter.println(aVideoGame.getName()+delim+
                                aVideoGame.getConsole());
        }
        fileWriter.close();
    }
    catch(Exception e)
    {
        System.out.println("Error");
    }
}
//returns an array list of video games based on a search criterion (name and console)
public void PrintSearchCriteria(String nameInput, String consoleInput)
{

    for(VideoGame aVideoGame : games)
    {
        if(aVideoGame.getName().contains(nameInput) == true && aVideoGame.getConsole().contains(consoleInput) == true)
        {
            VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole()); 
            System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());

        }
        else if(aVideoGame.getName().contains(nameInput) == true && consoleInput.equalsIgnoreCase("*"))
        {
            VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole()); 
            System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());

        }
        else if(nameInput.equalsIgnoreCase("*") && aVideoGame.getConsole().contains(consoleInput) == true)
        {
            VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole()); 
            System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());

        }

    }
}

public void PrintCurrentResults(String fileName)
{
    for(VideoGame aVideoGame : games)
    {
        System.out.println(aVideoGame.getName()+delim+
                                aVideoGame.getConsole());
    }
}

}

主类

public class VideoGameFrontEnd {

public static void main(String[] args) {
    //create and connect scanner object to keyboard
    Scanner keyboard = new Scanner(System.in);
    VideoGameManager vG = new VideoGameManager();
    System.out.println("Welcome to the video game database!");
    boolean quit = false;
    try{
    while(quit == false)
    {



    System.out.println("Enter 1 to load the video game database");
    System.out.println("Enter 2 to search the database");
    System.out.println("Enter 3 to print current results");
    System.out.println("Enter 4 to print current results to file");
    System.out.println("Enter 0 to quit");
    int input = keyboard.nextInt();

    switch(input){
    case 0: input = 0;
        System.out.println("Good Bye");
        quit = true;
        break; 

    case 1: input = 1;
        System.out.println("Enter the file Name");
        String fileName = keyboard.next();
        vG.ReadGameFile(fileName);
        break;
    case 2: input = 2;
        System.out.println("Enter the name of the game or '*' for all names");
        String nameInput = keyboard.next();
        System.out.println("Enter the name of the console or '*' for all consoles");
        String consoleInput = keyboard.next();
        vG.PrintSearchCriteria(nameInput,consoleInput);

        break;
    case 3: input = 3; 
        //print current results
        break;
    case 4: input = 4;

        System.out.println("Enter the file name to print out.");
        String fileNamePrintToFile = keyboard.next();
        System.out.println("Append to file ? True or False");
        String appendToFile = keyboard.next();
        if(appendToFile.equalsIgnoreCase("true"))
        {
            vG.WriteToGameFile(fileNamePrintToFile, true);
        }
        else if(appendToFile.equalsIgnoreCase("false"))
        {
            vG.WriteToGameFile(fileNamePrintToFile, false);
        }
        else
        {
            System.out.println("Incorrect Response, auto shutdown");
            System.exit(0);
        }
    default: 
        break;

        }

    }
}
catch(Exception e)
{
    System.out.println("error");
    System.exit(0);
}

}

}

1 个答案:

答案 0 :(得分:0)

我建议记录框架,如log4j,slf4j等。或java标准日志工具。

如果你想知道,如何保存System.out.print或println发送的所有输出,这里是你可以实现的方法之一。

public static void main(String[] args) throws FileNotFoundException {
        PrintStream ps = new PrintStream("mylog.log");
        System.setOut(ps);
        System.out.println(String.format("%s: %s", new Date(),"Application Started"));
        System.out.println(String.format("%s: %s", new Date(),"Application Terminated"));
    }

输出会是这样的, enter image description here