我目前正在研究一种用于笔和纸rp游戏的遭遇生成器,称为D& D(Dungeons and dragons)。我有一个用记事本文件写的怪物档案。当用户完成使用他想要的过滤器并按下"生成"程序通过怪物过滤,用给定的怪物读取记事本文件并将其(它们)写入新的记事本文件,然后打开(使用runnable exec)。当我从记事本阅读并写入记事本时,这一切都按预期工作。然后我收到了测试人员的一些反馈,他们想要一些图片以及不同的文本格式。因此,我将存档文件更改为RTF(字垫/富文本文件),并将完成的文件更改为相同的格式。我现在的问题是程序只将一个怪物写入文件,即使它应该写两个或更多。
以下是读写器方法的代码
public void readerAndWriter()throws IOException
{
destination = "Encounter.rtf";
File EncounterFile = new File(source);
FileInputStream fis =new FileInputStream(EncounterFile);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter writer = new FileWriter(destination,true);
BufferedWriter out = new BufferedWriter(writer);
String aLine = null;
while((aLine = in.readLine())!= null)
{
out.write(aLine);
out.newLine();
}
in.close();
out.close();
}
以下是使用reader and writer方法
的方法的代码段if (monsters.get(t).getRace() == monsters.get(u).getRace())
{
if (monsters.get(t).getCr() + monsters.get(u).getCr() ==
getChosenCr())
{
readAndWrite.setSource(monsters.get(t).getFilePath());
readAndWrite.readerAndWriter();
readAndWrite.setSource(monsters.get(u).getFilePath());
readAndWrite.readerAndWriter();
correctMonster = true;
}
else
etc etc
所有提示和提示都表示赞赏。
答案 0 :(得分:0)
如果我理解你的代码是正确的,你只需将几个文件的内容相互追加(你的怪物文件)。你可以用文本文件来做到这一点,但RTF并不那么简单(我的猜测是你只看到第一个怪物,因为RTF忽略了明显附加到RTF内容的RTF文档)。相反,你必须
Document
实例。javax.swing.text.Document
s。正如ControlAltDel所评论的那样,您可以使用RTFEditorKit(示例代码略微改编自http://www.programcreek.com/java-api-examples/index.php?api=javax.swing.text.rtf.RTFEditorKit的示例5):
/**
* Reads the file specified by path and writes its text content to out.
* @param out Writer to output the text content
* @param path name of an RTF file to read from
*/
public void simpleRtfExample(Writer out, String path) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(path);
byte[] buffer = new byte[in.available()];
in.read(buffer, 0, in.available());
String input = new String(buffer);
String result = null;
try {
RTFEditorKit rtfEditor = new RTFEditorKit();
Document doc = rtfEditor.createDefaultDocument();
// read the source RTF into doc:
rtfEditor.read(new StringReader(input), doc, 0);
// Get the text of the document as String.
// Here you could use doc's API to access
// its content in a more sophisticated manner.
result = doc.getText(0,doc.getLength());
} catch (Exception e) {
e.printStackTrace();
}
out.write(result);
} finally {
IOUtils.closeQuietly(in);
}
}