java - 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();
}
}
}
解决方案
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
*/
推荐阅读
- android - 如何从联系人那里获取电子邮件
- spring-boot - Spring Boot 2 Security在登录时下载字体文件
- python - 在 Python 中拆分响应
- python - 我应该使用字典还是系列来保存一堆数据框?
- java - 如何附加到实时数据库中的数组列表?
- elasticsearch - 如何通过命令行获取 Kibana 索引模式的描述?
- xcode - 什么框架访问需要 NSBluetoothPeripheralUsageDescription 密钥的敏感用户数据
- python - Python - 如何同时使用 OpenCV2 和 OpenCV3
- php - Silverstripe 3 表格未执行
- java - 有没有办法知道系统可以交换线程的代码中所有可能的位置