这种方法为什么不打开文件并写入呢?

huangapple go评论58阅读模式
英文:

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 &lt; 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 &lt; arrayToWrite.length; i++) {
            outFS.println(arrayToWrite[i]);
        }

    }
}

huangapple
  • 本文由 发表于 2020年8月13日 02:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63382846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定