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();
}
}
}
System.out.println(names)? Do you know why it prints what it prints?namesto the file. you have to iterate over each element of the array and write them one by one.Arrays.toString(names)inprintln.“instead of". Use a text editor, not a word processing application, to type your code. And if you get an error, paste it in your question instead of letting us guess what the problem might be.