我正在尝试用Java编写一个程序,该程序接受CSV文件作为用户输入(作为文件名或文件路径)。该程序删除所有大于或等于3的空格,并用逗号替换。然后,程序将使用用户指定的名称将修改后的文件保存到新位置。我目前在从用户那里读取文件时遇到困难。当我提供输入文件时,我收到以下错误消息:
An error occurred: "C:\...\buzz (The filename, directory name, or volume label syntax is incorrect)"
以下是我运行该程序的主要方法:
package fileConverter;
import java.io.*;
import java.util.*;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file name or location:");
String inputFile = scanner.next();
System.out.println("Enter output file name or location:");
String outputFile = scanner.next();
try {
FileConverter.convertWhitespaceToComma(inputFile, outputFile);
System.out.println("Conversion complete. Output written to " + outputFile);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}
这个主要方法调用“FileConverter.java”,如下所示:
package fileConverter;
import java.io.*;
import java.util.regex.Pattern;
public class FileConverter {
public static void convertWhitespaceToComma(String inputFile, String outputFile) throws IOException {
// Create a regex pattern for matching whitespace sequences of length 3 or more
Pattern pattern = Pattern.compile("\\s{3,}");
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(outputFile);
BufferedWriter bw = new BufferedWriter(fw);
String line;
while ((line = br.readLine()) != null) {
// Replace all matched whitespace sequences with commas
String modifiedLine = line.replaceAll(pattern.pattern(), ",");
bw.write(modifiedLine);
bw.newLine();
}
bw.close();
fw.close();
br.close();
fr.close();
}
}
我有一个try-catch块,主要用于打印错误消息(
e.getMessage()
),这就是此错误消息的来源:
出现错误:“C:\…\buzz(文件名、目录名或卷标语法不正确)”
当我编译并运行程序时,终端会显示以下内容:
Enter file name or location:
"C:\...\buzz lightyear\...\File Converter\src\fileConverter\<filename.txt>"
Enter output file name or location:
An error occurred: "C:\Users\buzz (The filename, directory name, or volume label syntax is incorrect)
C:\...\buzz lightyear\...\File Converter>
我知道我的代码可能还有其他问题,但让我弄清楚这一点,我会努力解决剩下的问题!
欢迎提供任何帮助和/或建议。我只是想找出文件无法识别的原因。非常感谢。
作为一种解决方法,我尝试提供文件名而不是完整路径,但我收到了以下错误消息:
The system cannot find the file specified