Like in the method i have attached i have used practiceData.txt i am getting same results while using just practiceData in file constructor so is it ok to use file without any extension or txt is better?
private void saveData(String data) {
File file = new File(this.getFilesDir(), "practiceData.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data.getBytes());
saveStatus = "Data was successfully saved.";
} catch (java.io.IOException e) {
e.printStackTrace();
saveStatus = "Error occurred: " + e.toString();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
It doesn't matter what file extension you use, it just tells the OS how to open the file. So yes, you can use no extension and it will work just as well.
If you intend the file to be opened manually via another application, it may be helpful to use a standard extension however.
Related
I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.
I try to use the official Dropbox API for uploading a zip file to my account. My project is a desktop application (standard Java). My code looks like this:
public void uploadZipFile(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
try {
getClient(accessToken).uploadFile("/" + file.getName(), DbxWriteMode.add(), file.length(), fis);
} finally {
fis.close();
}
}
private DbxClient getClient(String accessToken) {
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig(Constants.APP_NAME, Locale.getDefault().toString());
return new DbxClient(dbxRequestConfig, accessToken);
}
And I call it:
File zipFile = new File("C:\\Test\\MyFile.zip");
try {
uploadZipFile(zipFile);
} catch (Exception e) {
e.printStackTrace();
}
The file is transferred without any problems but then I want to delete the file after synchronization:
File zipFile = new File("C:\\Test\\MyFile.zip");
try {
uploadZipFile(zipFile);
System.out.println(zipFile.delete());
} catch (Exception e) {
e.printStackTrace();
}
The file is transferred successfully again, but the file still exists in the local file system and the delete method returns false.
New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?
I need to update ini file in java using rest service.I could read file in browser but have no idea how to update it.Can anybody please help for the required method that would update my ini file.
dbform.java
public class dbform {
public List<db> getAlldb(){
List<db> dbList = null;
try {
File file = new File("test.ini"); // read ini file
if (!file.exists()) {
db DB = new db("dbname: test","password: test");
dbList = new ArrayList<db>();
dbList.add(DB);
savedbList(dbList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
dbList = (List<db>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dbList;
}
private void savedbList(List<db> dbList){
try {
File file = new File("test.ini");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dbList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try to use ini4j.
The [ini4j] is a simple Java API for handling configuration files in Windows .ini format. Additionally, the library includes Java Preferences API implementation based on the .ini file.
http://ini4j.sourceforge.net/
Check your code there seems to be some issue in the way you have called the function. You don't seem to be passing the dbList into the replaceData() function. Probably it will be something like this
public void replaceData(List<db> dbList){ return DBform.savedbList(dbList); }
I have a logging class for writing into a file in the app's internal storage space. Whenever the log file exceeds the size limit. For clearing the contents, I am closing the current FileOutputStream and creating a new stream with Write mode and closing it. Is there a way better way for accomplishing this:
public final void clearLog() throws IOException {
synchronized (this) {
FileOutputStream fos = null;
try {
// close the current log file stream
mFileOutputStream.close();
// create a stream in write mode
fos = mContext.openFileOutput(
LOG_FILE_NAME, Context.MODE_PRIVATE);
fos.close();
// create a new log file in append mode
createLogFile();
} catch (IOException ex) {
Log.e(THIS_FILE,
"Failed to clear log file:" + ex.getMessage());
} finally {
if (fos != null) {
fos.close();
}
}
}
}
You could also overwrite your file with nothing.
UPDATE:
There seems to be a better option with getFilesDir () Have a look at this question How to delete internal storage file in android?
Write empty data into file:
String string1 = "";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", false);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(string1);
fWriter.flush();
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
In this code:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE - for write new content. If TRUE - text append to existing file.
public void writetofile(String text){ // text is a string to be saved
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(text);
outputWriter.close();
readfromfile();
Toast.makeText(getApplicationContext(), "file saved successfully",
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
}
}