[英]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.