简体   繁体   English

如何在Java项目文件夹中创建.txt文件并将其写入

[英]How to create a .txt file within the java project folder and write to it

I am attempting to create a text file within my project folder (not within the src but the System library). 我试图在我的项目文件夹(而不是src而是系统库)中创建一个文本文件。 I have already created a print to display the proper info in the correct format. 我已经创建了打印,以正确的格式显示正确的信息。 I copied and pasted this and edited the "System.out.println" to "PrintWriter.println". 我复制并粘贴了此内容,然后将“ System.out.println”编辑为“ PrintWriter.println”。 I am not sure if this code is correct although it shows no errors. 我不确定此代码是否正确,尽管它没有显示任何错误。

try {
        File file = new File("SortedLists.txt");
        FileWriter w = new FileWriter("SortedLists.txt");
        writer = new PrintWriter(w);

        for(Team p: roster){
            writer.println("Team Name: "+p.gettName()+", "+p.gettAbrv());
            for(Riders r: p.getRide()) {
                writer.println(r);
            }
            writer.printf("Total Team Donations: %.2f$\n",p.getSumD());
        }
    }
    catch(IOException e) {
        System.out.println(e.getMessage());
    }
    finally {
        writer.close();
    }

If you want to know where is your created file, you simply write for example 如果您想知道创建的文件在哪里,只需编写例如

System.out.println(file.getAbsolutePath());

Furthermore, if you want to create a file in a relative path (say in a folder for example) you can do something like this: 此外,如果要在相对路径(例如在文件夹中)中创建文件,可以执行以下操作:

File folder = new File("folderName"); 
folder.mkdir(); // create a folder in your current work space
File file = new File(folder, "fileName.txt"); // put the file inside the folder
file.createNewFile(); // create the file

To set the path for the file create the file as follows: 要设置文件的路径,请如下创建文件:

String fileLocation = absolutePathToFile; 字符串fileLocation = absolutePathToFile;

File file = new File(Location); 文件文件=新文件(位置);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM