首页 > 解决方案 > Fileoutputstream 没有创建另一个文件

问题描述

我试图让我的程序创建另一个可以由用户命名的文件并打印出用户想要打印的随机数。不幸的是,当我运行我的程序时,它一直有效,直到我到达程序状态的最后一个“你想使用什么文件名”

“找不到文件 java.io.FileNotFoundException:(句柄无效)”

我想知道我能做些什么来让程序实际创建文件并让用户为文件选择自己的名称。

import java.io.*;
import java.util.*;

public class chooseRandNum{
    public static void main(String[] args){
        Random rand = new Random();
        Scanner key = new Scanner(System.in);
        System.out.println("How many random numbers do you want? ");
        int totalRand = key.nextInt();
        System.out.println("What is the smallest random number? ");
        int smallRand = key.nextInt();
        System.out.println("What is the largest random number? ");
        int largeRand = key.nextInt();
        System.out.println("What filename do you want to use? ");
        String fname = key.nextLine();

        File outputFile = new File(fname);
        PrintStream outputStream = null;

        try{
            outputStream = new PrintStream(outputFile);
        }

        catch (Exception e){
            System.out.println("File not found " + e);
            System.exit(1);
        }

        int n = rand.nextInt(largeRand - smallRand + 1);
        for(int i = 0; i <= 5; i++){
            for(int j = 0; j <= totalRand; j++){
                outputStream.print(n + ",");
            }
            outputStream.println();
        }   
    }
}

标签: javaoutputjava.util.scannerprintwriter

解决方案


String fname = key.nextLine();应该String fname = key.next();

代码还有其他问题,但这解决了问题中的问题。

来自 JavaDoc:

nextLine()

/**
 * Advances this scanner past the current line and returns the input
 * that was skipped.
 *
 * This method returns the rest of the current line, excluding any line
 * separator at the end. The position is set to the beginning of the next
 * line.
 *
 * <p>Since this method continues to search through the input looking
 * for a line separator, it may buffer all of the input searching for
 * the line to skip if no line separators are present.
 *
 * @return the line that was skipped
 * @throws NoSuchElementException if no line was found
 * @throws IllegalStateException if this scanner is closed
 */

next()

/**
 * Finds and returns the next complete token from this scanner.
 * A complete token is preceded and followed by input that matches
 * the delimiter pattern. This method may block while waiting for input
 * to scan, even if a previous invocation of {@link #hasNext} returned
 * {@code true}.
 *
 * @return the next token
 * @throws NoSuchElementException if no more tokens are available
 * @throws IllegalStateException if this scanner is closed
 * @see java.util.Iterator
 */

推荐阅读