How can I edit the content of a file located on the internal storage in my Android app.
I want to erase the whole content and then write to the file again, instead of appending data to the current content.
Here's my code to read and write:
package com.example.cargom;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class FileManager {
FileOutputStream outputStream;
FileInputStream inputStream;
public void writeToFile(Context context, String fileName, String data) {
try {
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFromFile(Context context, String fileName) {
String data = "";
int c;
try {
inputStream = context.openFileInput(fileName);
while ((c = inputStream.read()) != -1) {
data = data + Character.toString((char) c);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
Your class is already doing what you rquire. It first erases the contents of the file and then writes on it. For further understanding,
When you initiate your stream with MODE_PRIVATE, the second time when you try to write the file, the contents that are already in the file gets erased and the new contents are written.
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
When you use MODE_APPEND, the contents that are already there stays and the new contents will be appended to the file.
outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
For more reference and detailed knowledge on dealing with files in Internal storage, I recommend you to watch the below three short videos which gives you detailed description with demo.
http://www.youtube.com/watch?v=Jswr6tkv8ro&index=4&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
http://www.youtube.com/watch?v=cGxHphBjTBk&index=5&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
http://www.youtube.com/watch?v=mMcrj_To18k&index=6&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
Hope it helps! Any more questions, please comment below.
You can just delete the file first with:
File f = new File(filename);
if(f.exists()){
f.delete();
}
And then create a new one with same path/name and write to it.
I'm assuming that your filename is the path to the file on the device.
But probably I'm not getting your real problem?
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 want to get a file from resources folder if it exists and create it there if it doesn't. I want to access it as file. class.getResource() doesn't work as it returns an URL. class.getResourceAsStream() gives input stream, but then I can't write in it or can I somehow?
import java.io.File;
import java.io.FileNotFoundException;
public class Statistika {
File file;
public Statistika() {
try {
file = Statistika.class.getResourceAsStream("statistics.txt");
} catch (FileNotFoundException e) {
file = new File("statistics.txt");
}
}
How to make this work?
Try using Statistika.class.getClassLoader().getResource(filename);If it returns null then you can create new file/directory. If your accessing this from jar then use Statistika.class.getClassLoader().getResourceAsStream(filename);
Hope it will solve your problem. Let me know if you found any difficulties.
Have you tried this?
File f = new File(Statistika.class.getResource("resource.name").toURI());
if (!f.isFile()){
f.getParentFile().mkdirs();
f.createNewFile();
}
Don't do file = new File("statistics.txt"); in your catch block .. just do the following
try {
File file = new File("statistics.txt");
InputStream fis = new FileInputStream(file);
fis = Statistika.class.getResourceAsStream(file.getName());
} catch (FileNotFoundException e) {
}
This is independent of whether the file exists or not.
File f = new File("statistics.txt");
try {
f.createNewFile();
} catch (IOException ex) { }
InputStream fis = new FileInputStream(f);
Use BufferedReader to insert contents to file referenced by f.
I have tried many examples from the same question that has already been asked including:
IOUtils.copy();
(copy is a non-existent method)
Files.copy(source, target, REPLACE_EXISTING);
(REPLACE_EXISTING "Cannot find Symbol")
FileUtils.copyFile();
(FileUtils doesn't exist)
The problems with using them are in brackets.
Here is the code for the most repeated method for copying:
import static java.nio.file.Files;
public void Install()
{
CrtFol();
CrtImgFol();
CrtSaveFol();
CrtSaveFile();
open.runmm();
//I have added the import for "Files"
Files.copy(img1, d4, REPLACE_EXISTING);
//Compiler says "Cannot find symbol" when I go over REPLACE_EXISTING
//img1 is a File and d4 is a File as a directory
}
Are there any other ways to copy or a way to fix the one above?
With Java 7's standard library, you can use java.nio.file.Files.copy(Path source, Path target, CopyOption... options). No need to add additional dependencies or implement your own.
try {
Files.copy( Paths.get( sFrom ),
Paths.get( sTo ),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Handle exception
}
Not sure if Java actually has anything to copy a file. The simplest way would be to convert the file into a byte stream and then write this stream to another file. Something like this:
InputStream inStream = null;
OutputStream outStream = null;
File inputFile =new File("inputFile.txt");
File outputFile =new File("outputFile.txt");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int fileLength;
while ((fileLength = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, fileLength );
}
inStream.close();
outStream.close();
where inputFile is the file being copied from, and outputFile is the name of the copy.
I use this code:
import java.io.*;
public class CopyTest {
public CopyTest() {
}
public static void main(String[] args) {
try {
File stockInputFile = new File("C://test.txt");
File StockOutputFile = new File("C://output.txt");
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count = 0;
while((count = fis.read()) > -1){
fos.write(count);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsReadnWrite: " + e);
} catch (IOException e) {
System.err.println("FileStreamsReadnWrite: " + e);
}
}
}
Use this code to upload file, I am working on SpringBoot...
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
#Component
public class FileUploadhelper {
public final String uploadDirectory = "D:\\SpringBoot Project\\BootRestBooks\\src\\main\\resources\\static\\image";
public boolean uploadFile(MultipartFile mf) {
boolean flag = false;
try {
Files.copy(mf.getInputStream(), Paths.get(uploadDirectory + "\\" + mf.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
I have used this code
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FTPClientExample {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("hostname");
client.login("user", "pwd");
String filename = "D:\\Task\\try.txt";
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
when i run this,i get the message task complete.But i couldnt find out which folder i should look for the file.some one pls help me?
you are trying to upload on the path D:\\Task\\try.txt .I guess that is your source file path.
You should write something like
client.storeFile(ftpPath + filename, fis);
where ftpPath should be the FTP server location where you want to upload the file.
Edit:: File path structure
ftp://"+username+":"+password+"#"+ip+"/"+dir+"/"+fileName
OK change
String filename = "D:\\Task\\try.txt";
to String filename = "/home/user_name/Desktop";where user_name is your user name for linux .. give it a try the file should be on your Desktop and remember linux is case sensitive.
In case of linux the path String filename = "D:\\Task\\try.txt"; changes to String filename = "/media/your_drive_name/try.txt";
here is linux directory structure explained.
I am trying to store a byteArrayInputStream as File on a FTP Server. I could already connect to the Server and change the working path, but triggering the method to store the Stream as File on the Server returns always false.
I am using the apache FTPClient.
Can someone please give me a hint where my mistake can be!?
Here the Code:
String filename = "xyz.xml"
// connection returns true
connectToFtpServer(ftpHost, ftpUser, ftpPassword, exportDirectory);
// byteArray is not void
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
try {
// change returns true
result = ftpClient.changeWorkingDirectory(exportDirectory);
// storing the file returns false
result = ftpClient.storeFile(filename, byteArrayInputStream);
byteArrayInputStream.close();
ftpClient.logout();
} catch (...) {
...
} finally {
// disconnect returns true
disconnectFromFtpServer();
}
I don't believe it's your code. Here is another example that looks very similar from kodejava:
package org.kodejava.example.commons.net;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FileUploadDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I agree it's file permissions. There is not a way to change permissions in java itself yet, but there are other solutions. See this thread: How do i programmatically change file permissions?
HTH,
James
It was actually a permission issue due to an invalid usergroup. After adding my user to the usergroup, i was able to store again files.