问题是它发现关键字“dodge”创建了文件但没有写入它。我之前遇到过这个问题,我刷新然后关闭文件修复了它,但这次不起作用。
另外 WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]);
向底部出错并显示 ArrayIndexOutOfBoundsException: -2
我不知道为什么因为“using”永远不应该出现在位置-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();
}
}
谢谢,马凯尔
编辑:我发现我只是编写一个字符串,创建一个新文件,然后编写另一个字符。我怎样才能不删除该文件,而只是重写它?
最佳答案
How can i not delete the file, and just rewrite to it?
我假设您的意思是附加到它。 (您当前正在做的是重写它。)
如果是这样,只需使用 FileWriter(file, true)
创建一个 Writer ,它将在文件的当前末尾开始写入;例如
CharacterFile = new PrintWriter(new FileWriter(new File(CurrentLine[3])));
<小时/>
注意:Java 变量或方法名称以大写字母开头是不好的风格。
关于java - 简单但冗长的 Java PrintWriter 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4360588/