简体   繁体   中英

What is the meaning of the compiler error “variable x may not have been initialized”

I'm trying to write a Java Android program that can read and write to a file. I'm having some issues though. When the line at the very end is run, Eclipse tells me that my totalString variable may not have been initialized. However, I assign it a value inside the try loop. When I remove that last line and run my program, my console displays "Read File Successfully", as well as "java.io.FileInputStream@d77ffd1". That's definitely not the value I wrote to the file. I don't know what I'm doing wrong here and I'm kind of losing my mind lmao. Additionally, if I try to put a line like

totalString = "A Test Value"

In the try block, I still get the same error. Any help would be greatly appreciated.

            //lets try WRITING the file

            Context context = getApplicationContext();
            String filename = "balance";
            String balanceString = "0.00";
            FileOutputStream outputStream;
            try {
                outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
                outputStream.write(balanceString.getBytes());
                outputStream.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                System.out.println("Error in Writing File.");
            }

            //lets try READING the file
            String totalString;
            FileInputStream inputStream;
            try {
                inputStream = openFileInput(filename);
                inputStream.read();
                inputStream.close();
                totalString = inputStream.toString();
                System.out.println("Read File Successfully");
                System.out.println(totalString);
            }
            catch (Exception e) {
                e.printStackTrace();
                System.out.println("Error in Reading File.");
            }
            System.out.println(totalString);

inputStream.read() MIGHT throw an Exception. In this case, the variable MIGHT not have be initialized. Just change the declaration to

String totalString = null;

Alternatively you can move the System.out.println to the end of the try-block, where, when reached because no Exception is thrown, the variable is initialized.

inputStream.toString() returns a string representing the id of the InputStream object . Not the data inside the file.

If you want the data inside the File which you are reading from the InputStream , you need to use built-in methods to read the file. The easiest way to do so is to wrap the InputStream object inside a BufferedReader (or any other Reader object), then use the .readLine() (or equivalent) method to get the data.

For example:

String totalString;
BufferedReader in;
try {
     in = new BufferedReader(new InputStreamReader(openFileInput(filename)));
     totalString = in.readLine();
     in.close();
     System.out.println("Read File Successfully");
     System.out.println(totalString);
    }
catch (Exception e) {
     e.printStackTrace();
     System.out.println("Error in Reading File.");
    }

Now for output:

You could use the exact same technique as before, only changing the objects to their 'Writer' equivalents. For example:

PrintWriter out;
try {
     out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(penFileOutput(filename, Context.MODE_PRIVATE))));
     out.println(balanceString);
     out.flush();
     out.close();
    }
catch (Exception e) {
     e.printStackTrace();
     System.out.println("Error in Writing File.");
    }

The purpose of using the PrintWriter here in addition to the BufferedWriter is because it provides very easy to use methods (ie println() ). Also, the 'flush()' method is used to make sure all the data in the stream gets written to the file, rather than 'getting stuck' in the buffer.

EDIT: Forgot to add a 'new' before the BufferedReader above. Fixed.

Also, read some tutorials about reading and writing files.

inputStream.read() will read a byte from the stream. But if you don't assign the return value of that function to a variable, it is discarded.

inputStream.toString() does what it says. It tries to describe the object, not the contents of the stream.

I would do it like that

  FileOutputStream outputStream=new FileOutputStream(filename);

    ObjectOutputStream stringSaver = new ObjectOutputStream(outputStream);   

   stringSaver.writeObject(balanceString); 
   stringSaver.close();   
    outputStream.close();

All this in a try catch for saving in a file the String then load it with

         FileInputStream inputStream = new FileInputStream(filename);  
         ObjectInputStream objectStream = new ObjectInputStream(inputStream);   
         totalString = (String) objectStream.readObject();
         objectStream.close();
        inputStream.close();

this also in try catch... It should work. The problem solves that there was one variable may not have been initialized.

When you dont understand one part of the code be free to ask :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM