问题是它会找到关键字"dodge“来创建文件,但不会写入文件。我之前遇到过这个问题,我刷新然后关闭文件解决了这个问题,但这次没有起作用。
另外,在底部使用错误,并说ArrayIndexOutOfBoundsException: -2,我不确定为什么,因为“WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]);”永远不应该出现在位置-1。
import java.io.*;
import javax.swing.JOptionPane;
public class InputLog {
private BufferedReader CombatLog;
private PrintWriter CharacterFile;
private String[] CurrentLine;
InputLog(){
try{
CombatLog = new BufferedReader(new FileReader("127401175162_chatlog.txt"));
do{
try{
CurrentLine = CombatLog.readLine().split(" ");
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry cannot open UserSettings File");
}
DetermineType();
}while(CombatLog.ready());
CharacterFile.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Could not open next line of combatlog " + e);
}
}
public void WriteToFile(String S){
try{
CharacterFile = new PrintWriter(new File(CurrentLine[3]));
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry can't write " + CurrentLine[3] +" To file");
}
CharacterFile.flush();
CharacterFile.print(S+ " ");
}
public void WriteToFileLn(String S){
try{
CharacterFile = new PrintWriter(new File(CurrentLine[3]));
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry can't write " + CurrentLine[3] +" To file");
}
CharacterFile.flush();
CharacterFile.println(S+ " ");
}
public int ReturnWordsIndex(String S){
for(int i=0;i<CurrentLine.length;i++){
if(CurrentLine[i].equals(S))
return i;
}
return -1;
}
private void DetermineType(){
for(String A: CurrentLine)
if(A.equals("attacks")){
JOptionPane.showMessageDialog(null, "found dodge");
WriteToFile(CurrentLine[2]);
WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]);
WriteToFile("(dodge).");
WriteToFileLn(CurrentLine[ReturnWordsIndex("attacks")-1]);
}
}
public static void main(String args[]){
new InputLog();
}
}谢谢你,麦凯尔
编辑:我发现我只是在写一个字符串,创建一个新文件,然后再写另一个字符。我怎么能不删除文件,而只是重写它呢?
发布于 2010-12-06 07:32:24
我怎么能不删除文件,而只是重写它呢?
我假设你的意思是附加到它上面。(您当前正在做的是重写它。)
如果是这样,只需使用FileWriter(file, true)创建一个Writer,它将在文件的当前末尾开始写入;例如
CharacterFile = new PrintWriter(new FileWriter(new File(CurrentLine[3])));注意: Java变量或方法名以大写字母开头是不好的风格。
发布于 2010-12-06 03:09:59
WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]);会导致使用,因为没有找到单词“ArrayIndexOutOfBoundsException: -2”(因此ReturnWordsIndex("using")返回-1)。
您需要一个if/then语句,以便在未找到单词时不会尝试对CurrentLine进行索引。
发布于 2010-12-06 07:15:23
为了响应您的编辑,请在WriteToFile和WriteToFileLn函数外部打开文件。
https://stackoverflow.com/questions/4360588
复制相似问题