如何创建可以再次读取的文本文件?

时间:2014-01-23 21:10:01

标签: java import

我参加了一个关于Java的基础课,但我的知识很少。自从我越来越熟悉Java以来​​,我在过去的一两个月里创建了一个基于文本的RPG。我想知道是否有任何方法可以让程序创建一个“保存”文件存储在某个文件夹中,并提示用户是否要打开已保存的字符。我还没有学过Java的任何面向对象的部分。我该怎么做才能实现这个目标?

2 个答案:

答案 0 :(得分:1)

  

我想知道是否有任何方法可以让程序创建一个   “保存”文件存储在某个文件夹中并提示用户是否   他们想打开一个保存的角色。

编写和阅读文本文件是保存游戏状态的一种坚实的初学者方式。

write to files listed here有很多方法,但这里有一个例子:

PrintWriter out = new PrintWriter("filename.txt");//create the writer object
out.println(text);//write
out.close() //when you're done writing, this will save

现在,这是一种读取文件found from here的简单方法:

BufferedReader br = new BufferedReader(new FileReader("filename.txt"));//objects to read with
try {
    StringBuilder sb = new StringBuilder();//use to build a giant string from the file
    String line = br.readLine();

    //loop file line by line
    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();//always close!
}

网上有很多教程只是谷歌。 | = ^]

注意Always remember to close readers/writers/scanners/etc. Else wise you'll get resource errors which you can read more about here.

答案 1 :(得分:-1)

这是我为保存文本而构建的类,

import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Savetext {

    /**
     * Saves text to a <i>.txt</i> file with the specified name,
     * 
     * @param name the file name without the extension
     * 
     * @param txt the text to be written in the file
     * 
     * @param message the message to be displayed when done saving, if <tt>null</tt> no
     * message will be displayed
     */
    public static void Save(String name, String txt, String message) {
        name += ".txt";
        gtxt(name, txt, message);
    }

    private static void gtxt(String name, String txt, String mess) {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        File file = null;
        fc.showSaveDialog(null);
        file = fc.getSelectedFile();
        String path = file.getPath();
        path += "\\";
        path += name;

        File f1 = new File(path);
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new FileWriter(f1)));
            wrtxt(out, txt, mess);
        } catch (IOException e) {

            JOptionPane.showMessageDialog(null, e.getMessage().toString());
        }

    }

    private static void wrtxt(PrintWriter out, String txt, String mess) {
        out.println(txt);
        out.flush();
        out.close();
        if (mess != null)
            JOptionPane.showMessageDialog(null, mess);
    }

}

你应该调用 static save()方法,而不需要创建类的实例,