2

It's been awhile since I've created and written to a file. I've created the file and I've written to it but I get some weird characters. The only numbers that should be in the file are -1, 0, and 1.

Now I get the numbers I need, but I need them to displayed as a 2d array in the text file.

Example:

     -1 -1 -1 -1 -1
     -1 -1 -1 -1 -1
     -1 -1 -1 -1 -1

Please help

public void saveFile()
{
   String save = "Testing";
   JFileChooser fc = new JFileChooser();
   int returnVal = fc.showSaveDialog(null);


    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");

            for(int row = 0; row < gameArray.length; row++)
           {
               for(int col =0; col < gameArray[row].length; col++)
               {
                  bw.write(String.valueOf(gameArray[row][col]));
               }
           }
            bw.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

2
  • 2
    The data is being written: however, you are writing it as binary data. Commented May 1, 2014 at 7:13
  • It's unclear what you actually need. If you want a text file that contains the textual values of the ints then you need to convert to a String. If not, then you can use a DataOutputStream to write the 4-byte int value. Commented May 1, 2014 at 7:42

3 Answers 3

2

From documentation of write(int c) method

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

In other words you are passing index of character from Unicode table.

What you probably need is

fw.write(String.valueOf(gameArray[row][col]));

which will first convert your integer to String and write its characters.

Also consider wrapping your writer with PrintWriter which has methods like print, println (similar to System.out) so you could just use

fw.print(gameArray[row][col]);
Sign up to request clarification or add additional context in comments.

4 Comments

@user2864740 What do you mean? docs.oracle.com/javase/8/docs/api/java/io/…
Failing on my part. :|
So when you write to files, they're automatically stored as Strings within the file?
@user2906074 Purpose of Writers is writing characters. If you are interested in writing bytes then you should use Streams
2

I suggest that you use a BufferedWriter instead as it is easier.

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Also, you do not need to append a .txt, AFAIK, because JFileChooser will return the full name.

SSCCE:

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) {
        try {

            String content = "This is the content to write into file";

            File file = new File("/users/mkyong/filename.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content,0,content.length());
            bw.close();

            System.out.println("Done");

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

taken from Mykong.

Comments

0

Check the documentation, write with an integer argument writes a single character. I guess your gameArray has integer elements.

Convert the elements to a string and also take care to add a space between the numbers. Something like

fw.write(" " + gameArray[row][col]);

will work.

3 Comments

@user2864740 Have a look at my answer.
@user2864740: by wrapping the FileWriter into a PrintWriter, and using its various print() methods.
@JBNizet or just a PrintWriter and avoid the wrapping hassle? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.