不创建文件(Java)

时间:2015-06-26 17:44:49

标签: java file bufferedwriter

出于某种原因,我在编译代码时不断收到以下错误。我有正确的预处理器指令(import语句),没有语法错误,但每当我编译我的代码时,我都会得到

2 个答案:

答案 0 :(得分:0)

可能,你的dateFile是空的,这可能是造成这种异常的原因

public int nextInt()

将输入的下一个标记扫描为int。 调用nextInt()

形式的此方法

返回: 从输入中扫描的int

抛出: InputMismatchException - 如果下一个标记与整数正则表达式不匹配,或者超出范围

NoSuchElementException - 如果输入已用尽

IllegalStateException - 如果此扫描程序已关闭

参考http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)

答案 1 :(得分:0)

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()您的缓冲区..如果您希望它在关闭之前写在文件上! 请注意,我更改了文件的路径以使其在我的电脑上工作,因此请再次更改