【发布时间】:2015-10-09 01:06:21
【问题描述】:
我试图将控制台输出到一个文本文件,当询问用户想要输出到哪个文件时,用户可以创建/命名该文本文件,但由于某种原因,它只在控制台中显示结果。有没有办法将输出发送到 Eclipse 内部的新文本文件?这是我写的代码。
代码:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Project03 {
public static void main(String[] args) throws FileNotFoundException {
CaesarCipher CaesarCipher = new CaesarCipher("", 0);
Scanner choice = new Scanner(System.in);
Scanner intoff = new Scanner(System.in);
Scanner output = new Scanner(System.in);
System.out.println("Type E to encrypt a file, or D to decrypt a file");
String pick = choice.nextLine();
if (pick.toLowerCase().equals("e")) {
System.out.println("Enter the file path of the text you'd like to encrypt: ");
File file = new File(choice.nextLine());
Scanner textfile = new Scanner(file);
String line = textfile.nextLine();
System.out.println("Enter the offset you would like to use (must be 1-25)");
int offset = intoff.nextInt();
System.out.println("Name the file you would like to output to");
String TextOutput = output.nextLine();
System.out.println(CaesarCipher.encode(line, offset));
PrintStream out = new PrintStream(new FileOutputStream(TextOutput));
System.setOut(out);
} else if (pick.toLowerCase().equals("d")) {
System.out.println("Enter the file path of the text you'd like to decrypt: ");
File file = new File(choice.nextLine());
Scanner textfile = new Scanner(file);
String line = textfile.nextLine();
System.out.println("Enter the offset you would like to use (must be 1-25)");
int offset = choice.nextInt();
System.out.println("Name the file you would like to output to");
String TextOutput = output.nextLine();
System.out.println(CaesarCipher.decode(line, offset));
PrintStream out = new PrintStream(new FileOutputStream(TextOutput));
System.setOut(out);
} else {
System.out.println("Something went Wrong");
}
}
}
【问题讨论】:
-
您只需要先创建文件并将其包含在 eclipse 中。
-
你知道你应该在写之前设置
System.out,否则它不会重定向?此外,您可能应该使用简单的Writer或OutputStream,看看Basic I/O。您也不需要三个Scanners 都从相同的输入中读取,他们都会同时看到相同的东西...... -
“有没有办法将输出发送到 Eclipse 内部的新文本文件?” - 我认为这不是一个好主意,如果用户输入“C:\MyTextFile.txt”?然后应该将文件写入用户指示它的任何位置。如果用户没有提供路径,那么它将被写入执行程序的同一位置。如果他们提供的路径不存在,那么你就有麻烦了;)
标签: java eclipse file output text-files