有没有办法从命令行读取输入并将其写入文本文件?
public class Tester
{
public static void main(String[] args)
{
//Yes, I am clueless so I have no idea what to put
}
}
答案 0 :(得分:1)
因为我假设你是Java的初学者,所以我写了一个带有不言自明的注释的简短代码示例。应用程序在命令行上运行并逐行读取,其中一行通过按Enter键结束。如果键入“EXIT”,应用程序将退出。要写入的文本文件位于C:\Folder\Text.txt
。
这是一个非常基本的示例,因此只需将其扩展到您的需求即可。为了获得更好的平台独立性,您可以用\\
替换硬编码的File.separator
斜杠。作为finally块的注释:在较新版本的Java(> = 7)中,您可以使用try-with
语法保存大量样板代码。如果您有兴趣,请阅读更多相关信息here。
您可以在教程here中了解基本的I / O机制。
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
// The reader and writer objects must be declared BEFORE
// the try block, otherwise they are not 'visible' to close
// in the finally block
Scanner reader = null;
FileWriter writer = null;
String inputText;
try {
// Reader and writer are instantiated within the try block,
// because they can already throw an IOException
reader = new Scanner(System.in);
// Do not forget, '\\' is the escape sequence for a backslash
writer = new FileWriter("C:\\Folder\\Text.txt");
// We read line by line, a line ends with a newline character
// (in Java a '\n') and then we write it into the file
while (true) {
inputText = reader.nextLine();
// If you type 'EXIT', the application quits
if (inputText.equals("EXIT")) {
break;
}
writer.write(inputText);
// Add the newline character, because it is cut off by
// the reader, when reading a whole line
writer.write("\n");
}
} catch (IOException e) {
// This exception may occur while reading or writing a line
System.out.println("A fatal exception occurred!");
} finally {
// The finally branch is ALWAYS executed after the try
// or potential catch block execution
if (reader != null) {
reader.close();
}
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
// This second catch block is a clumsy notation we need in Java,
// because the 'close()' call can itself throw an IOException.
System.out.println("Closing was not successful.");
}
}
}
}
答案 1 :(得分:0)
使用Java 8,这可以非常简洁:
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Stream<String> stream = in.lines().limit(20); // 20 is number of lines you want to read
try (PrintWriter pw = new PrintWriter("FileName.txt", "UTF-8")) {
stream.map(s -> s)
.forEachOrdered(pw::println);
}
catch (UnsupportedEncodingException | FileNotFoundException e) {
e.printStackTrace();
}