android NULL values after reading a file into array

1.4k views Asked by At

first of all i need to create text file in internal storage(if file does not exists) and then to read values line by line into array. I do not understand what i do wrong, why my reading from internal memory is not detecting my file and how should i fix that? (I suppose creating file and writing to it is correct)

How i want my data file to look like:

data
data
data
data
data
data

How I write values to file:

        FileOutputStream fOut = null;
        try {
            fOut = openFileOutput("VilniusWeatherVU.txt",MODE_WORLD_READABLE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String v33 = "data";
        String v12 = "data";
        String v3 = "data";
        String v11 = "data";
        String v6 = "data";
        String v1 = "data";

        try {
            fOut.write(v33.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.write(v12.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.write(v3.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.write(v11.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.write(v6.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.write(v1.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

How i read values:

String[] array = new String[6];
        int index = 0;
        try{
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("VilniusWeatherVU.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // Print the content on the console
                //System.out.println (strLine);
                array[index]=strLine;
                index++;
            }
            //Close the input stream
            in.close();
        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

How i check my array:

    for (int i = 0; i <6; i++){
       Log.v(LOG_TAG, "CHECK IF IT WORKED " + array[i]);
   }

What my logcat says:

11-24 16:06:56.886      359-359/app.sunshine.android.example.com.sunshine W/System.err﹕ Error: /VilniusWeatherVU.txt (No such file or directory)
11-24 16:06:56.895      359-359/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED null
11-24 16:06:56.895      359-359/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED null
11-24 16:06:56.895      359-359/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED null
11-24 16:06:56.895      359-359/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED null
11-24 16:06:56.895      359-359/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED null
11-24 16:06:56.895      359-359/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED null

please don't leave me alone on this one :(

Frunk requested:

i attempt to read from file in a different way:

        FileInputStream fin = null;
        try {
            fin = openFileInput("VilniusWeatherVU.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int c;
        String temp="";
        try {
            while( (c = fin.read()) != -1){
                temp = temp + Character.toString((char)c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//string temp contains all the data of the file.
        try {
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

then i use logcat to check:

Log.v(LOG_TAG, "CHECK IF IT WORKED " + temp);

and what i get is:

11-24 16:24:38.345      334-334/app.sunshine.android.example.com.sunshine V/MyNewMain﹕ CHECK IF IT WORKED datadatadatadatadatadata
3

There are 3 answers

9
Ludger On BEST ANSWER
public class MyFragment extends Fragment
    {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        {
            view = inflater.inflate(R.layout.myfragment, container, false);


            writeFile("text.txt", view.getContext());
            String[] test = readFile("text.txt", view.getContext());
            if(test==null)
            {
              // error to read file or file dont exists
            }else
            {
              //read file
            }    
            return view;
        }

 public static String   newline = System.getProperty("line.separator");

// write file
private void writeFile(String filename, Context context)
{

    File file = new File(context.getFilesDir(), filename);

    // write data if file dont exists
    if (!file.exists())
    {
        String string = "data" + newline + "data" + newline + "data"
                + newline + "data" + newline + "data" + newline + "data"
                + newline;

        FileOutputStream outputStream;

        try
        {
            outputStream = context.openFileOutput(filename,
                    Context.MODE_PRIVATE);
            outputStream.write(string.getBytes());
            outputStream.close();

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

// read file and convert data to String array
private String[] readFile(String filename, Context context)
{
    try
    {
        File file = new File(context.getFilesDir(), filename);
        if (!file.exists())
        {
            return null;
        }
        FileInputStream fis = new FileInputStream(file);
        byte[] dataByte = new byte[(int) file.length()];
        fis.read(dataByte);
        fis.close();
        String data = new String(dataByte);
        // slit string with newline <\n>

        return data.split(newline);
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;


}
}
3
Miki Franko On

try to use openFileInput("VilniusWeatherVU.txt") for read your file txt.

for example:

FileInputStream fileInputStream= openFileInput("VilniusWeatherVU.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder= new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    stringBuilder.append(line);
}
4
greenapps On
fOut = openFileOutput("VilniusWeatherVU.txt",MODE_WORLD_READABLE);

does not match with

FileInputStream fstream = new FileInputStream("VilniusWeatherVU.txt");

Better: To read the file use a full path using getFilesDir() as the directory where your file is stored.