由于某些原因,我在编译代码时不断出现以下错误。我有正确的预处理器指令(导入语句),没有语法错误,但每当我编译代码时,我都会得到
可能,您的dateFile为空,这可能是导致异常的原因
public int nextInt()
将输入的下一个标记扫描为int。此方法的调用形式为nextInt()
退货:从输入扫描的int
投掷:InputMismatchException-如果下一个令牌与Integer正则表达式不匹配,或者超出范围
NoSuchElementException-如果输入已耗尽
IllegalStateException-如果此扫描仪已关闭
参考http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Reader
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
File dateFile = new File("test.txt");
FileWriter fw = new FileWriter(dateFile);
BufferedWriter bw = new BufferedWriter(fw);
Scanner reader = new Scanner(dateFile);
try
{
// if file doesnt exists, then create it
if (!dateFile.exists())
{
dateFile.createNewFile();
bw.write("1");
bw.close();
System.out.println("Done");
}else
{
int duration;
String ans = JOptionPane.showInputDialog ("Enter the amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the amount of problems per training session (with number in minutes):" );
}
duration = Integer.parseInt(ans);
System.out.println(duration);
bw.write(""+duration);
bw.flush();
int numSessions = reader.nextInt();
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File(""+fileName+".txt");
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
System.out.println("IT DOES NOT EXIST!");
}
fw = new FileWriter(newSession.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(duration);
bw.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
现在它应该起作用了。我加上这两行:
bw.write(""+duration);
bw.flush();
你从来没有写在档案里。记住.flush()你的缓冲区。。如果你想在关闭它之前把它写在文件上!注意,我更改了文件的路径,让它在我的电脑上工作,所以再次更改