Java 将字符串数组插入文本文件

标签 java arrays file

我正在尝试使用字符串数组中的信息创建一个文本文件,到目前为止我已经完成了所有操作,但是将数组作为内容放入文本文件中。任何帮助将不胜感激,我已经复制了迄今为止涉及的所有代码。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;




public class WriteToFileExample
{
public static void main(String[] args)
{
    String newDir = "new_dir";

        boolean success = (new File(newDir)).mkdir();
        newDir = "/Volumes/Mav/Names/";
        success = (new File(newDir)).mkdirs();
        File filename = new File("/Volumes/Mav/Names/javaprogramming.txt");

        if (success) 
        {
            System.out.println("Successfully created the file at directory " + filename);
        }   

        else 
        {
            System.out.println("An error occurred creating the directory or file " + filename + ". Please contact your System Administrator.");
        }

        try 
        {
            String[] names = {“John”, “Matthew”, “Luke”, “Peter”};

            if (!filename.exists()) 
            {
                filename.createNewFile();
            }

            FileWriter fw = new FileWriter(filename.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(names);
            bw.close();


        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
}
}

最佳答案

看起来您可能有 smart quotes在你的数组中。智能引号对于 Java 引号无效(我想在 Word 中对 Java 进行编程非常困难)...

String[] names = {"John", "Matthew", "Luke", "Peter"};

您可以迭代数组并将每个名称写入文件,

for (int i = 0; i < names.length; i++) {
  if (i != 0) bw.write(", ");
  String name = names[i];
  bw.write(name);
}

但您可能更喜欢使用Arrays#toString像这样-

 bw.write(java.util.Arrays.toString(names));

关于Java 将字符串数组插入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487325/

相关文章:

java - 在Spring中生成一致的资源链接

javascript - 读取状态数组 ReactJS

c - 在 C 中越界访问数组不会产生运行时错误

c++ - Windows 上的直接文件系统函数调用

file - 在 MSI 中解压、修改和重新打包文件?

java - 懒人登录

java - 有人看到这个线程模式有什么问题吗?

Python 用 'numpy.ndarray' 创建一个字典

php - 读取php文件并查找mysql

java - 我应该使用哪个类加载器?