【发布时间】:2018-05-11 18:48:34
【问题描述】:
我有以下方法:
public static void main(String[] args)
{
DataWriter.addScore(2, DataWriter.score(8.5,2.25, 170.0);
}
还有这个类,DataWriter:
public class DataWriter
{
public static int findTextInFile(String s) //returns an int representing the line number of String s
{
try
{
int ln = 0;
File data = new File("data.txt");
String line = null;
Scanner fileInput = new Scanner(data);
while(fileInput.hasNextLine())
{
String prevLine = fileInput.nextLine();
ln++;
if(prevLine.equals(s))
{
// br.close();
return ln;
}
}
//br.close();
}
catch(Exception e) { System.out.println(e); }
return 0;
}
public static void addScore(int prompt, String stats) //Calls the WriteAfterNthLine method with a prompt number and stats string.
{
try
{
switch(prompt)
{
case 1:
writeAfterNthLine("data.txt", stats, findTextInFile("NORMAL"));
break;
case 2:
writeAfterNthLine("data.txt", stats, findTextInFile("SMALL"));
break;
case 3:
writeAfterNthLine("data.txt", stats, findTextInFile("NUMBERS"));
break;
case 4:
writeAfterNthLine("data.txt", stats, findTextInFile("COMMON WORDS"));
break;
case 5:
writeAfterNthLine("data.txt", stats, findTextInFile("OTHER"));
break;
default:
System.out.println("ERROR INVALID SUBMISSION");
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void writeAfterNthLine(String filename, String text, int lineno) throws IOException //Writes String to filename on line lineno
{
//TODO:Document this method.
File file = new File(filename);
File tmpDir = new File("C:/Users/jacobw4107/Documents/EZType"); //This is the current directory.
System.out.println("Made temporary Directory " +tmpDir);
File temp = File.createTempFile("temp-file-name", ".tmp", tmpDir);
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
System.out.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
File old = new File("data.old");
if(old.exists())
System.out.println(old.delete());
System.out.println(file.renameTo(new File("data.old")));
System.out.println(temp.renameTo(new File("data.txt")));
}
}
当我自己调用 writeAfterNthLine 方法时,一切正常。但是,运行上面的 main 方法会导致 writeAfterNthLine 方法的最后两行失败。最后两行和 renameto 行失败,并返回 false。如果我尝试手动重命名 data.txt,则会出现以下错误:
无法完成该操作,因为该文件已在 Java(TM) Platform SE 二进制文件中打开。
那么锁定文件的方法是什么?
我运行的是 Windows 10 教育版 1703。我确实没有拥有管理员权限。
【问题讨论】: