I want to create String to txt file that i got from textfield. the file created but it's always empty. i don't know what is wrong. it's work if i manually write the string : out.write("text"), but when i took the text from textview, it's always empty. please help.
this is code to created file :
String fname = t2.getText().toString()+".txt";
String text = t3.getText().toString();
String fpath = t.getText().toString();
try {
File root = new File(fpath);
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fname);
FileWriter writer = new FileWriter(gpxfile);
PrintWriter out = new PrintWriter(writer);
out.println(text);
out.flush();
out.close();
Toast.makeText(getBaseContext(), "Berhasil menyimpan", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
break;
this is where text = t3.getText().toString() came from :
t3 = (TextView)findViewById(R.id.saveText);
Related
public void newEditSportRecord(){
String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
File oldFile = new File(filepath);
System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\sport.txt
File newFile = new File(tempFile);
System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\temp.txt
String ID, name = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
while (x.hasNextLine()) {
ID = x.next();
System.out.println(ID);
name = x.next();
System.out.println(name);
if (ID.equals(editTerm)) {
newID = JOptionPane.showInputDialog("Enter new Sport ID:");
newName = JOptionPane.showInputDialog("Enter new Sport Name:");
pw.println(newID);
pw.println(newName);
pw.println();
JOptionPane.showMessageDialog(modifySport, "Record Modified");
} else {
pw.println(ID);
pw.println(name);
pw.println();
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception ex) {
JOptionPane.showMessageDialog(modifySport, ex);
}
}
I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?
Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.
I am getting this error in my code when trying to read a file saved on the external storage of my phone :
java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)
I can manage to write data to this file with success, what I did a lot of times.
However, I cannot access for reading this same file, giving the entire path or through another method.
The code writing and saving successfully :
File path = new File(this.getFilesDir().getPath());
String value = "vegetables";
// File output = new File(path + File.separator + fileName);
File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
// Toast.makeText(getBaseContext(), "File saved successfully!",
// Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Chemin fichier = [" + output + "]");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The writing piece of code crashing my app :
try
{
File gFile;
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
//FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;
Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
reader.close();
fis.close();
Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
//return input;
}
catch (IOException e)
{
Log.e("Exception", "File read failed: " + e.toString());
//toast("Error loading file: " + ex.getLocalizedMessage());
}
What am I doing wrong ?
For sure, not a problem of permissions, since I can write with success.
Many thanks for your help.
You missed to specifiy the correct path. You are looking for a file named shopping.txt in your current working directory (at runtime).
Create a new File object with the correct path and it will work:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");. You could reuse your object from writing.
While opening the file, you are simply using new File("shopping.txt").
You need to specify the parent folder, like this:
new File(getExternalFilesDir(),"shopping.txt");
I recommend you make sure of org.apache.commons.io for IO, their FileUtils and FileNameUtils libs are great. ie: FileUtils.writeStringToFile(new File(path), data); Add this to gradle if you wish to use it: implementation 'org.apache.commons:commons-collections4:4.1'
In regards to your problem. When you write your file you are using:
getApplicationContext().getExternalFilesDir(null),"shopping.txt"
But when reading your file you are using:
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
Notice that you didn't specify a path to shopping.txt simply the file name.
Why not do something like this instead:
//Get path to directory of your choice
public String GetStorageDirectoryPath()
{
String envPath = Environment.getExternalStorageDirectory().toString();
String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
return path;
}
//Concat filename with path
public String GetFilenameFullPath(String fileName){
return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}
//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);
//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
text.append(line);
if(newLine)
text.append(System.getProperty("line.separator"));
}
br.close();
Trying to get a list of files so that I can name the next file based on how many are already there. The idea is similar to downloading multiple files with the same name. Eg:
filename.txt
filename(1).txt
filename(2).txt
etc...
this is the current method I am using, which returns a list of strings.
private List<String> getFilenames(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("json");
#Override
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0){
for (File file : filesFound){
list.add(file.getName());
}
}
return list;
Once I have the list I'm thinking I can use the list.length method to figure out which number I need to put in the filename.
Here is where I am creating the file.
JSONObject jsonToSave = createJSONObject();
String filepath = "fileStorage";
List<String> filenames = getFilenames(filepath);
int filenameNumber = filenames.size() + 1;
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
filename = "newAssessment(" + filenameNumber + ").json";
internalFile = new File(directory , filename);
try {
FileOutputStream fos = new FileOutputStream(internalFile);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(jsonToSave.toString());
osw.close();
Context context = getApplicationContext();
CharSequence text = "Assessment saved!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
catch (IOException e){
e.printStackTrace();
}
the createJSONObject just creates a json object with the data that needs to be saved.
I can confirm the the application is getting to the Toast that is in the try block after the OutputStreamWriter is closed, so the file is saving.
The problem that I am having is when trying to populate a ListView in another activity with some of the data from the files, nothing appears on listview. I have tested with success reading a single file.
I'm using the same getFilenames method as above, then using FileInputStream to read the data from the files, parse it into a json object, add some fields from each file to an array, and then update an android listview with the array.
Heres the code:
filenames = getFilenames(filepath);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
for (String filename : filenames) {
internalFile = new File(directory, filename);
try {
FileInputStream fis = new FileInputStream(internalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String assessmentDate = "";
String orchard = "";
String strLine;
int dataCounter = 0;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
try {
JSONObject object = new JSONObject(myData);
assessmentDate = object.getString("assessmentDate");
orchard = object.getString("orchard");
} catch (JSONException e) {
e.printStackTrace();
}
data.add(dataCounter, assessmentDate + " : " + orchard);
dataCounter++;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
LVAssessments.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data));
Any help is much appreciated, thank you.
I have this method that takes one String and writes it to a file. I set the PrintWriter to true because I want to save all the data that is written to it.
I want to have headings on this file. How can I write the headlines to the file and only do it one time?
My method looks like this:
public static void writeToFile(String text) {
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter("test", true);
writer.write(text);
writer.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
It's not clear whether your file has multiple heading or not. Assuming your file has only one heading we can do this as follow -
1. Since your file contain heading only one time, you can check whether the file is accessing for the first time -
File f = new File(//your file name);
if(f.exists() && !f.isDirectory()) {
//write heading
}
2. If the file is first time accessed then you can add a header -
String heading = "Some heading";
The full code looks like -
public static void writeToFile(String text) {
String heading = "Some heading";
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter(f, true);
if(f.exists() && !f.isDirectory()) {
writer.write(heading);
}
writer.write(text);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}finally{
writer.close();
}
}
You can use BufferWriter to write a sentence and take a look at a better way to handle the file.
try {
String content = "This is the content to write into file";
File f = new File("test.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}finally{
writer.close();
}
}
What I have so far:
A block of code that intakes a username and password and write it to a textfile.
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
try {
FileWriter userInfoWriter = new FileWriter(usernameFilename);
BufferedWriter writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.write("\r\n" + writePassword);
writeToFile.close();
What I need to accomplish:
Create a directory to a pre-made folder called users.
Save the file to usernameFilename to a directory.
What I've tried:
I've searched online everywhere! I cant find anything to do this :c
Extra info:
Since all computers are different, I would like to use the .getAbsolutePath() method when creating the directory.
Take a look at:
java.io.File
File#exists
File#isDirectory
File#mkDirs
You could update your code to look more look this...
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
File users = new File("users");
if ((users.exists() && users.isDirectory()) || users.mkdirs()) {
FileWriter userInfoWriter = null;
BufferedWriter writeToFile = null;
try {
userInfoWriter = new FileWriter(users.getPath() + File.seperator + usernameFilename);
writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.newLine();
writeToFile.write(writePassword);
//....
} finally {
try {
writeToFile.close();
} catch (Exception exp) {
}
}
} else {
throw new IOException("Could not create/find Users directory");
}