how to save text to file in Android Studio? - java

I want to create file in which the first line will be constantly updated. actually I want to save this file to custom path, for example /storage/emulated/0/Download, but I don't know how to do that, so now I have something like this:
public void save(){
while(true) {
try {
String FILENAME = "my_file";
String string = "" + System.currentTimeMillis();
FileOutputStream fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(string.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
and this code gives me two errors
Cannot resolve method 'openFileOutput'
Cannot resolve symbol 'MODE_PRIVATE'

FileOutputStream fos = getApplicationContext().getContextResolver().openFileOutput(FILENAME);
Before using openFileOutpout() you have to use getContextResolver() and there is no Context.MODE_PRIVATE parameter in this function

Related

How to write and constantly update a text file in Android

I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}

How to load the correct language (set in config) instead of the language last in an array

I'm creating a little java app and I'm trying to load the yml files based on config.yml lang set (en/it) but I can't find a way to load them, only the last one in an array is loaded which is "it" for me.
I know that my method is probably the worst solution for a language file, I'm open to every method that will help me with the problem. But I prefer an external lang_en/it file instead of internal ones (Or is it better internal?)
After I set the language, the app will self-update every text in every class.
static final Properties props = new Properties();
static WelcomeMessage main = new WelcomeMessage();
static File file = null;
static File folder = null;
static boolean os = main.os.startsWith("Windows");
public static void create() {
String[] lang = {"en", "it"};
for (String s : lang) {
file = new File(WelcomeMessage.user + "/AppData/Roaming/MyApp/lang_" + s + ".yml");
folder = new File(file.getParent());
SetLanguages(s);
}
if (!file.exists()) {
try {
if (os) {
folder.mkdir();
file.createNewFile();
} else {
file = new File(main.user + "/Library/Application Support/MyApp/config.yml");
folder.mkdir();
file.createNewFile();
}
} catch (Exception e) {
System.out.println(e + " " + file);
}
}
}
public static void SetLanguages(String lang) {
if (lang.equals("en")) {
store("Settings.Save", "Save");
store("Settings.ConfigPath", "Config Path");
store("Settings.Language", "Language");
store("Settings.Title", "Settings");
} else if (lang.equals("it")) {
store("Settings.Save", "Salva");
store("Settings.ConfigPath", "Percorso config");
store("Settings.Language", "Lingua");
store("Settings.Title", "Impostazioni");
}
}
public static String get(String value) {
String key = null;
try {
FileInputStream in = new FileInputStream(file);
props.load(in);
key = props.getProperty(value);
in.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
return key;
}
public static void store(String value, String key) {
try {
FileOutputStream out = new FileOutputStream(file);
props.setProperty(value, key);
props.store(out, null);
out.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
}
This is how I get a text from yml:
path.setText(Language.get("Settings.ConfigPath"));
language.setText(Language.get("Settings.Language"));
f.setTitle(Language.get("Settings.Title"));
save.setText(Language.get("Settings.Save"));
And this my Language.get(key)
public static String get(String value) {
String key = null;
try {
FileInputStream in = new FileInputStream(file);
props.load(in);
key = props.getProperty(value);
in.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
return key;
}
I suggest the following changes:
Create a Settings class to hold the properties save, configPath, language and title. Even better if this class uses an immutable builder pattern, because once set, the properties will never change.
Create a SettingsFactory class with method getSettings(language). This class shall also have a field Map<String, Settings>. In the constructor (or a static block), first check if a file exists on the disk, and if yes, load it into the map. If not, populate the map, one entry for each language, and persist to the disk.
getSettings would simply return the value from the map corresponding to the given language.
The format of the file written to the disk is a different matter. You say YAML, but I'm not seeing any YAML specific code in your snippet. If you don't know how to write a map to YAML, open a different question.

Cannot Write String to FileWriter/BufferedWriter

I am trying to make an application that will create Google Authenticator secret keys, as well as authenticate the OTP. I am writing all of my passwords to individual files titled with the name that goes along with them.
First and foremost, I am using this library.
https://github.com/aerogear/aerogear-otp-java
This is my code:
public void createUserFile(String name) throws IOException
{
File file = new File("users\\" + name + ".txt");
file.createNewFile();
}
public void generateUserKey(String name)
{
try
{
File file = new File("users\\" + name + ".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fw);
String s = Base32.random();
out.write(s);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
If I change the value of s to something like "Hello" I am fine. However, it will not write that random string. That is what I need help with. I have tinkered and searched hours for answers, and I have found nothing.
I don't believe you need createUserFile, and it isn't clear you necessarily know where the "users/" folder (a relative path) is. I suggest you use System.getProperty(String) to get user.home (the User home directory).
I would also suggest you use a try-with-resources Statement and a PrintStream. Something like
public void generateUserKey(String name) {
File file = new File(System.getProperty("user.home"), //
String.format("%s.txt", name));
try (PrintStream ps = new PrintStream(file)) {
ps.print(Base32.random());
} catch (IOException e) {
e.printStackTrace();
}
}

JEditorpane cannot load URL

I have problem with my JEditorPane, cannot load URL, always show java.io.FileNotFoundException. Totally I am confused how to solve it.
JEditorPane editorpane = new JEditorPane();
editorpane.setEditable(false);
String backslash="\\";
String itemcode="a91000mf";
int ctr=6;
File file = new File("file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode+"&jumlah="+String.valueOf(ctr)+"&lokasi=../images");
if (file != null) {
try {
//editorpane.addPropertyChangeListener(propertyName, listener)
editorpane.setPage(file.toURL());
System.out.println(file.toString());
} catch (IOException e) {
System.err.println(e.toString());
}
} else {
System.err.println("Couldn't find file: TextSamplerDemoHelp.html");
}
I just put "file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode", but it will show its same error : cannot open file, but I can open it in my browser
File expects a local file path, but "file://...." is a URI... so try this:
URI uri = new URI("file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode+"&jumlah="+String.valueOf(ctr)+"&lokasi=../images");
File file = new File(uri);
You should remove all usage of the File class.
A string which starts with "file:" is a URL, not a file name. It is not a valid argument to a File constructor.
You are calling the JEditor.setPage method which takes a URL, not a File. There is no reason to create a File instance:
try {
URL url = new URL("file:///C:/Development/project2/OfflineSales/test/index.html?item_code=" + itemcode + "&jumlah=" + ctr + "&lokasi=../images");
editorpane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
JEditorPane also has a convenience method which does the conversion of a String into a URL for you, so you can even skip the use of the URL class entirely:
String url = "file:///C:/Development/project2/OfflineSales/test/index.html?item_code=" + itemcode + "&jumlah=" + ctr + "&lokasi=../images";
try {
editorpane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
(Notice that String.valueOf is not needed. It is implicitly invoked whenever you concatenate a String with any object or primitive value.)

When writing to file in Java the file cannot be saved in folders

What im trying to do is simply letting the user choose a directory to save a text file to, Problem is im trying to select a folder im creating on my desktop but when i select the folder with the JFileChooser and letting the code i have do the work it's still saved outside the folder and into the desktop.. Why? Can someone please explain what i did wrong so i might learn something..
public class TextFileSaver {
String filePath;//Used in the setPath and getPath methods
String filename = File.separator+"tmp"; //Used for the JFileChoosers directory
public TextFileSaver(){
//Get our file saver to the screen
JFileChooser fc = new JFileChooser(new File(filename));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //Only able to select directiories
// Show open dialog; this method does not return until the dialog is closed
fc.showSaveDialog(null);
File selectedLocation = fc.getCurrentDirectory(); //Gets the selected Location
//Sets the path of the file so we can read from it.
setPath(selectedLocation.getAbsolutePath());
FileName();
try {
SaveFile(filePath);
}
catch (IOException ex) {
Logger.getLogger(TextFileSaver.class.getName()).log(Level.SEVERE, null, ex);
//Show a message dialog
JOptionPane.showMessageDialog(null, "The file could not be saved, Please try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setPath(String Path){
filePath = Path;
}
public String getPath(){
return filePath;
}
private void FileName(){
String name = JOptionPane.showInputDialog
("What name do you want to give the file?");
//Temporary code bellow will change to StringBuilder here.
filePath = filePath + "/" + name + ".txt";
}
private void SaveFile(String Path) throws IOException{
System.out.println(Path);
//The outStream that we will use to write to the text file the user is creating.
PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(Path)));
outStream.println("Test text!");
outStream.close();
}
}
All the methods are executed through the constructor.. So the code happends step by step..
Use getSelectedFile() and not getCurrentDirectory() and also, you should append your filePath somewhere.

Categories

Resources