How would I be able to create a new file which will have a different file name each time? Would it also be possible to add line breaks when writing to these files? Also, how would I be able to access this file?
package com.example.create_recipe;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
EditText editTxtRecipeName, editTxtEquipment, editTxtIngredients, editTxtMethod, editPersonalStory;
Spinner spnCountries, spnHours, spnMinutes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createRecipe(Context context) throws FileNotFoundException {
//TODO Create new file - should it be named after the recipe name or a unique int id?
String recipeName = editTxtRecipeName.getText().toString();
String country = spnCountries.getSelectedItem().toString();
String hours = spnHours.getSelectedItem().toString();
String minutes = spnMinutes.getSelectedItem().toString();
String equipment = editTxtEquipment.getText().toString();
String ingredients = editTxtIngredients.getText().toString();
String method = editTxtMethod.getText().toString();
String personalStory = editPersonalStory.getText().toString();
//TODO Write to file, adding new line breaks between recipeName, equipment and so on.
}
}
2
Answers
WHat you need is an UUID and use it like so
Please note
Environment.getExternalStorageDirectory()
will not work post API 29. This example is just meant to show the use of UUID to generate unique values to storeGetting your app directory (ContextWrapper is an Application/Activity/Service):
Obtaining the complete file path:
Obtaining a file-object:
Saving a byte array:
Or a file:
In java, linebreaks use the character ‘n’, you can use that.
Load a byte array using String name:
Or a file:
You’ll have to come up for a system to name your files. To check if a file exists, just create the file object and call
For naming your files, you’ll need to come up with a system. If recipeName is unique, you can use that. You’ll find something that uniquely identifies your Recipe.