簡體   English   中英

如何在Java項目文件夾中創建.txt文件並將其寫入

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

我試圖在我的項目文件夾(而不是src而是系統庫)中創建一個文本文件。 我已經創建了打印,以正確的格式顯示正確的信息。 我復制並粘貼了此內容,然后將“ System.out.println”編輯為“ PrintWriter.println”。 我不確定此代碼是否正確,盡管它沒有顯示任何錯誤。

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();
    }

如果您想知道創建的文件在哪里,只需編寫例如

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

此外,如果要在相對路徑(例如在文件夾中)中創建文件,可以執行以下操作:

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

要設置文件的路徑,請如下創建文件:

字符串fileLocation = absolutePathToFile;

文件文件=新文件(位置);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM