是否可以在程序中创建fileIO?

时间:2015-12-05 12:52:36

标签: java file-io

我有一堆代码现在已经演变成一个功能齐全的控制台(大部分)游戏。我现在很好奇,如果我想实现一个输入/输出功能,我是否必须在另一个文件中创建它,或者我可以将它放在与我的代码相同的类中。例如,我的讲师为编写用于保存名称的fileIO的示例如下:

import java.io.*;

class savenames
{
   public static void main(String[] params) throws IOException 
   {
       PrintWriter outputStream = new PrintWriter(new FileWriter("mydata.txt"));

       // Create an array with some sample names to store
       String [] names = {"Paul", "Jo", "Mo"};

       // Store the names from the array in the file, one name per line    
       for (int i = 0; i < names.length; i++)
       {
               outputStream.println(names[i]);
       }  
       outputStream.close();
       System.exit(0);
   }
} 

这附带以下代码(在不同的文件中):

import java.io.*;

class readnames
{
   public static void main(String[] params) throws IOException 
   {
       BufferedReader inStream = new BufferedReader(new FileReader("mydata.txt"));
       String [] names = new String[3];
       System.out.println("The names in the file mydata.txt are:");

       for (int i = 0; i < names.length; i++)
       {
           names[i] = inStream.readLine();
           System.out.println(names[i]);
       }
       inStream.close();
       System.exit(0);
   }
} 

我只是想知道是否可以在同一个文件中执行这两项操作,因为我的代码有许多不同的方法,而且我不确定如何制作一个单独的方法来执行此操作。感谢。

编辑:也许我可以修改这个问题,使它更好一点。

我的桌面游戏中有以下主要方法:

class newminip
{
   public static void main (String[] params) throws IOException
   { 
       numberPlayers();
       int diceroll = dicethrow(6);
       int[] scorep1 = scorearrayp1();
       questions(diceroll, scorep1);
       sort(scorep1);
       System.exit(0);
   }  

   .... insert code here ....

   public static void exitmethod(int[] scorep1)
   {
      sort(scorep1);
      for (int i = 0; i < 4; i++)
      {
         System.out.println("Player " + (i+1) + " scored " + scorep1[i] + "");
      }
      System.exit(0);
   }

} //END class

我想要一些可以将分数保存到新文本文件中的东西。我希望这让它变得更加清晰。

2 个答案:

答案 0 :(得分:1)

是的,你可以在一个文件中完成。我为它创建了一个新类:

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

public class FileIO {

    public static String[] readStringsFromFile(final String filename) throws IOException {
        BufferedReader inStream = new BufferedReader(new FileReader(filename));

        //Use ArrayList since you don't know how many lines there are in the file
        ArrayList<String> lines = new ArrayList<String>();

        String line;
        //Read until you reach the end of the file
        while ((line = inStream.readLine()) != null) {
            lines.add(line);
        }
        inStream.close();

        //Convert it back to a string array
        return lines.toArray(new String[lines.size()]);
    }

    public static void writeStringsToFile(String[] lines, final String filename) throws IOException {
        PrintWriter outputStream = new PrintWriter(new FileWriter(filename));

        for (int i = 0; i < lines.length; i++) {
            outputStream.println(lines[i]);
        }
        outputStream.close();
    }

    public static void main(String[] args) {
        //To test the methods:
        //Create an array to write to the file
        String[] linesToWrite = {"firstLine", "secondLine", "thirdLine"};
        try {
            //Write the strings to a file named "testfile.txt"
            writeStringsToFile(linesToWrite, "testfile.txt");

            //Read all lines of a file named "testfile.txt"
            String[] readLines = readStringsFromFile("testfile.txt");

            //Print out the read lines
            for (String line : readLines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error msg");
        }
    }
}

本例中的主要方法是测试,您可以将其删除并将其他两种方法复制到您的类中。这可能不是执行文件io的最佳或最有效的方法,但在你的情况下,这应该做的工作(: 编辑: 因此,如果您只需要读取文件的整数,就可以使用以下内容:

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

public class FileIO {

    public static Integer[] readIntegersFromFile(final String filename) throws IOException {
        BufferedReader inStream = new BufferedReader(new FileReader(filename));

        //Use ArrayList since you don't know how many lines there are in the file
        ArrayList<Integer> integers = new ArrayList<Integer>();

        String line;
        //Read until you reach the end of the file
        while ((line = inStream.readLine()) != null) {
            //Parse integers form read string values
            integers.add(Integer.parseInt(line));
        }
        inStream.close();

        return integers.toArray(new Integer[integers.size()]);
    }

    public static void writeIntegersToFile(Integer[] lines, final String filename) throws IOException {
        PrintWriter outputStream = new PrintWriter(new FileWriter(filename));

        for (int i = 0; i < lines.length; i++) {
            outputStream.println(lines[i]);
        }
        outputStream.close();
    }

    public static void main(String[] args) {
        //To test the methods:
        //Create an array to write to the file
        Integer[] linesToWrite = {1, 100, 15};
        try {
            //Write the strings to a file named "testfile.txt"
            writeStringsToFile(linesToWrite, "testfile.txt");

            //Read all lines of a file named "testfile.txt"
            Integer[] readLines = readStringsFromFile("testfile.txt");

            //Print out the read lines
            for (int line : readLines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error msg");
        }
    }
}

答案 1 :(得分:-1)

您可以使用两种主要方法中的代码创建Java文件,并删除System.exit(0);,因为您不需要它。这样一个程序就可以做到这两点。我建议你在尝试阅读之前先编写文件。

将所有内容放在一个程序中会使文件的使用相当多余,但在这种情况下,您只需打印数组即可。