如何使用 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
如果您验证该文件,您可以观察到包含数组内容的文件 −
广告