Java将String数组插入到文本文件中

时间:2014-01-31 18:23:00

标签: java arrays file

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

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();
        }
}
}

2 个答案:

答案 0 :(得分:2)

您的数组中似乎有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));

答案 1 :(得分:1)

我的朋友请提出你的字符串

像这样

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

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

并且来自一方的一个建议必须让一个最终阻止关闭你的资源而不是试图在try块中关闭它们