I'm trying to create a directory in internal storage and then write my files in that directory. I'm able to create the directory in internal storage but it is not showing.
When I create new file in that directory and write in that file, I get an error of null pointer exception. File.createNewFile() method is ignored and my file is not created. I'm using printwriter to write in file and buffered reader to read. How to read and write files in internal storage?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_monday);
//Creating directory and file
File internalPath = Environment.getDataDirectory();
myDir = new File("/data/", "Directory");
if(!myDir.exists()) {
myDir.mkdir();
Log.d(TAG, "Dir created");
}
monExerciseFile = new File(myDir, "Work_Monday.txt");
if(!monExerciseFile.exists()) {
try {
boolean a = monExerciseFile.createNewFile();
//monExerciseFile.createNewFile(); I have tried this statement also
Log.d(TAG, "File created");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "File not created");
}
}
//Printwriter
try {
printWriter = new PrintWriter(monExerciseFile);
} catch (IOException e) {
e.printStackTrace();
}
//Setting toolbar for monday activity
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar_monday);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setTitle(R.string.exercise_monday);
}
}
public void addExercise(View view) {
EditText et = (EditText) findViewById(R.id.m_child_et_1);
String exerciseToBeWritten = String.valueOf(et.getText());
printWriter.println(exerciseToBeWritten);
try{
BufferedReader br = new BufferedReader(new FileReader(monExerciseFile));
Log.d("ExerciseMonday.class", br.readLine());
}catch(Exception e){
e.printStackTrace();
}
}
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.PrintWriter.println(java.lang.String)' on a null object reference