CoShark
CoShark

Reputation: 129

Java Insert String array into text file

I am trying to create a text file with information from a String array and I have accomplished everything so far, but getting the array into the text file as content. Any help would be greatly appreciated and I have copied all of the code involved so far.

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

Upvotes: 0

Views: 2462

Answers (2)

Girish
Girish

Reputation: 1717

My friend please intiallize your string

like this

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

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

and one suggestion from side u have to make one finally block to close your resource not try to close them in try block

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201477

It looks like you may have smart quotes in your array. Smart quotes are not valid for Java quotes (and I imagine it's very difficult to program Java in Word)...

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

You can iterate over the array and write each name to the file,

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

but you may prefer to use Arrays#toString like this -

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

Upvotes: 2

Related Questions