尝试创建和写入文件,但我收到错误消息

时间:2017-06-08 17:59:41

标签: java file filewriter bufferedwriter file-writing

我试图学习如何创建一个文件并在Java上写入它。我一直在网上观看有关如何操作的视频。不幸的是,使用与完成课程的人完全相同的代码,我想出了这些我不理解的错误。

java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at CompanyAdder.main(CompanyAdder.java:26)
java.io.FileNotFoundException: C:/Users/mychalco/Desktop/ASreader.txt (No such file or directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at java.io.FileWriter.<init>(FileWriter.java:90)
    at CompanyAdder.main(CompanyAdder.java:35)

我知道第26和35行显然有错误,但我不明白还有什么事情发生。这是我的代码:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class CompanyAdder 
{
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        //String addCompanyName = "Y";
        //String companyName;

        File newFile = new File("C:/Users/mychalco/Desktop/ASreader.txt");

        if(newFile.exists())
        {
            System.out.println("The file already exists");
        }
        else
        {
            try
            {
                newFile.createNewFile();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            try
            {
                FileWriter fileW = new FileWriter(newFile);
                BufferedWriter buffW = new BufferedWriter(fileW);
                /*System.out.println("Add a company name: ");

                while (addCompanyName.equalsIgnoreCase("Y"))
                {
                    companyName = sc.next();
                    buffW.write(companyName);
                    System.out.println("Do you want to add another company? (Y/N) ");
                    addCompanyName = sc.next();
                }*/
                buffW.close();
                System.out.println("Company names added!");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

}

忽略评论行,这些是我试图对代码做出的一些改动。

谢谢,干杯。

1 个答案:

答案 0 :(得分:0)

尝试以这种方式使用File.separator

File newFile = new File("C:"+File.separator+"Users"+File.separator+"mychalco"+File.separator+"Desktop"+File.separator+"ASreader.txt");