I am trying to create a program where it takes simple input and writes it to a file. Problem is, when it tries to open the file to write to it, I get the error: "java.io.FileNotFoundException: C:\Users\bobdu\eclipse-workspace\SHIPTesting.txt (The filename, directory name, or volume label syntax is incorrect)." I even have a very simple program where I get the same error:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class OutputTesting {
public static void main(String[] args)
{
try
{
PrintWriter outputStream = new PrintWriter(new FileOutputStream("C:\\Users\\bobdu\\eclipse-workspace\\SHIPTesting.txt"));
outputStream.println("Output line 1");
outputStream.println("Output line 2");
outputStream.close();
}
catch (FileNotFoundException e)
{
System.err.println(e.getMessage());
e.printStackTrace(System.err);
System.exit(0);
}
}
}
The file does exist for sure, I can find it in my directory. Thank you in advance for helping me.
解决方案
You have an extra non-printable character in your path string. It survived the copy paste as well, so i was able to reproduce your error. Here is a test:
String yours = "C:\\Users\\bobdu\\eclipse-workspace\\SHIPTesting.txt";
String retyp = "C:\\Users\\bobdu\\eclipse-workspace\\SHIPTesting.txt";
System.out.println("yours len="+yours.length()+", retype=" + retyp.length());
The output is
yours len=49, retype=48
博主分享了一个Java程序中尝试打开并写入文件时遇到的FileNotFoundException,原因在于路径字符串中包含非打印字符。通过测试代码发现,问题出在复制粘贴过程中引入的额外字符。解决方法是确保路径字符串正确无误。
1万+

被折叠的 条评论
为什么被折叠?



