英文:
How come this method does not open up a file and write to it?
问题
I created this method with the intention of populating a txt file named "filename" with the elements present in the "arrayToWrite." However, it appears that the method is not functioning as expected. Could it be possible that the file is being deleted once the method concludes? This seems to be my primary concern, as my other method seems unable to display the contents from the file generated by this particular method.
public static void writeFile(String[] arrayToWrite, String filename) throws IOException{
FileOutputStream fileStream = new FileOutputStream(filename);
PrintWriter outFS = new PrintWriter(fileStream);
for (int i = 0; i < arrayToWrite.length; i++) {
outFS.println(arrayToWrite[i]);
}
}
英文:
I made this method and my goal is to populate a txt file of name filename with the elements that are contained in arrayToWrite, but it does not seem to be working. Does the file get deleted once the method ends? because that is my main issue it would seem my other method can not print the content that is in the file made by this method.
public static void writeFile(String[] arrayToWrite, String filename) throws IOException{
FileOutputStream fileStream = new FileOutputStream(filename);
PrintWriter outFS = new PrintWriter(fileStream);
for (int i = 0; i < arrayToWrite.length; i++) {
outFS.println(arrayToWrite[i]);
}
}
答案1
得分: 4
在你的函数末尾添加 outFS.close()
。
英文:
Add an outFS.close()
to the end of your function.
答案2
得分: 1
你可以在try-with-resources语句中声明一个或多个资源,FileOutputStream
类和PrintWriter
类都实现了AutoCloseable
接口,所以为了解决你的问题,你可以编写:
public static void writeFile(String[] arrayToWrite, String filename) throws IOException {
try (
FileOutputStream fileStream = new FileOutputStream(filename);
PrintWriter outFS = new PrintWriter(fileStream)
) {
for (int i = 0; i < arrayToWrite.length; i++) {
outFS.println(arrayToWrite[i]);
}
}
}
英文:
You may declare one or more resources in a try-with-resources statement and both FileOutputStream
class and PrintWriter
class implement the AutoCloseable
interface, so to solve your problem you can write :
public static void writeFile(String[] arrayToWrite, String filename) throws IOException {
try (
FileOutputStream fileStream = new FileOutputStream(filename);
PrintWriter outFS = new PrintWriter(fileStream)
) {
for (int i = 0; i < arrayToWrite.length; i++) {
outFS.println(arrayToWrite[i]);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论