Search code examples
javaandroid-studioexport-to-csvjava-io

Getting error "cannot find symbol class". Why?


Here's a program I've writing in Android Studio to write a CSV file. I keep receiving the error "Cannot find symbol class". I need help resolving that.

    File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir"); 
    if (!fileDir.exists()) {
        try {
            fileDir.mkdir();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    if (file.exists()) {
        try {
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bfWriter = new BufferedWriter(fileWriter);
            bfWriter.write("Text Data");
            bfWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Solution

  • If that is your complete program it can't compile because each file in Java needs to be a class and you didn't indicate it is a class. And if the class is to be invoked from the command line instead of just instantiated by another class, then you need to name your main entry point.

    I've added those things, but have not compiled it. The compiler may generate other errors if the code isn't perfect.

    See how that goes and then if you're still stuck update the question with more details and or ask a new more specific question. If this answer helps at all, please give it an up vote.

    import java.io.*;
    
    public class WriteCSV
    {
        public static void main(String args[])
        {
            File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir"); 
            if (!fileDir.exists()) {
                try {
                    fileDir.mkdir();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            if (file.exists()) {
                try {
                    FileWriter fileWriter = new FileWriter(file);
                    BufferedWriter bfWriter = new BufferedWriter(fileWriter);
                    bfWriter.write("Text Data");
                    bfWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }