如何使用 Java 将数组内容存储在文件中?


可以使用 Writer 类将数据写入文件。在下面给出的示例中,我们使用 BufferedWriter 编写数组的内容。

示例

在线演示

import java.io.BufferedWriter;
import java.io.FileWriter;

public class WritingStringArrayToFile {
   public static void main(String args[]) throws Exception {
      String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop", "Neo4j"};
      BufferedWriter writer = new BufferedWriter(new FileWriter("myFile.txt", false));
      for(int i = 0; i < myArray.length; i++) {
         writer.write(myArray[i].toString());
         writer.newLine();
      }
      writer.flush();
      System.out.println("Data Entered in to the file successfully");
   }
}

输出

Data Entered in to the file successfully

如果你检查该文件,你就会发现该文件包含数组内容 -

示例

在线演示

import java.io.BufferedWriter;
import java.io.FileWriter;

public class WritingIntArrayToFile {
   public static void main(String args[]) throws Exception {
      Integer[] myArray = {23, 93, 56, 92, 39};
      BufferedWriter writer = new BufferedWriter(new FileWriter("myFile.txt", false));
      for(int i = 0; i < myArray.length; i++) {
         writer.write(myArray[i].toString());
         writer.newLine();
      }
      writer.flush();
      System.out.println("Data Entered in to the file successfully");
   }
}

输出

Data Entered in to the file successfully

如果你检查该文件,你就会发现该文件包含数组内容 -

更新于:16-6-2020

2000+ 查看

开启你的职业

通过完成课程来获得认证

开始
广告