问题描述
当前,我的代码如下:
import java.util.*;
import java.io.*;
public class ShoppingList {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Invalid number of arguments.");
return;
}
String outputFile = args[0];
try {
Scanner scanIn = new Scanner(system.in);
File fileOut = new File(outputFile);
PrintWriter myWriter = new PrintWriter(fileOut);
fileOut.createNewFile();
while (true) {
String nextLine = scanIn.nextLine();
if (nextLine.equals("")) {
break;
}
myWriter.write(nextLine + "\n");
}
myWriter.close();
} catch (IOException e) {
System.err.println("IOException");
return;
}
}
}
当前,我的代码在输入流的末尾和程序的末尾之间留空行。 Link有什么办法摆脱那条线?谢谢!
解决方法
在写入文件时,请勿在输入的末尾添加换行符(\n
)
myWriter.write(nextLine + "\n");
相反,在将用户输入字符串添加到文件中之前,将其添加到文件中。是的,这将在将第一个用户输入行写入文件之前添加一个空行,因此您需要一种方法来确定是否已将行写入文件中。您可以通过多种方式来执行此操作,例如计数器,布尔标志等。
使用布尔标志:
public class ShoppingList {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Invalid number of arguments.");
return;
}
String outputFile = args[0];
try {
Scanner scanIn = new Scanner(System.in);
File fileOut = new File(outputFile);
java.io.PrintWriter myWriter = new java.io.PrintWriter(fileOut);
fileOut.createNewFile();
// Boolean Flag to determine if first line is written to file.
boolean firstLineWritten = false;
while (true) {
String nextLine = scanIn.nextLine().trim();
if (nextLine.equals("")) {
// Nothing provided by User - Close the file.
break;
}
// If a first line has been written...
if (firstLineWritten) {
// Add a system line separator to the file line previously written.
myWriter.write(System.lineSeparator());
}
// Add User Input to file (no newline character added)
myWriter.write(nextLine);
// Write the User input to the file right away!
myWriter.flush();
// Flag the fact that the first line is written.
firstLineWritten = true;
}
myWriter.close();
} catch (IOException e) {
System.err.println("IOException");
}
}
}
使用柜台:
public class ShoppingList {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Invalid number of arguments.");
return;
}
String outputFile = args[0];
try {
Scanner scanIn = new Scanner(System.in);
File fileOut = new File(outputFile);
java.io.PrintWriter myWriter = new java.io.PrintWriter(fileOut);
fileOut.createNewFile();
// A counter to determine if first line is written to file.
int lineCounter = 0;
while (true) {
String nextLine = scanIn.nextLine().trim();
if (nextLine.equals("")) {
// Nothing provided by User - Close the file.
break;
}
// If a first line has been written...
if (lineCounter > 0) {
// Add a system line separator to the file line previously written.
myWriter.write(System.lineSeparator());
}
// Add User Input to file (no newline character added)
myWriter.write(nextLine);
// Write the User input to the file right away!
myWriter.flush();
// Increment counter to the fact that the first line is written.
lineCounter++;
}
myWriter.close();
} catch (IOException e) {
System.err.println("IOException");
}
}
}