I made an android app which writes to a file in an activity.
The writing to file, it works like a charm:
FileOutputStream fOut = openFileOutput("myfeeds.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(file);
osw.flush();
osw.close();
But when I want to read it back from another acivity it can't find the file...the file exists I checked with DDMS file explorer.
Reading file contents:
FileInputStream fis = new FileInputStream("myfeeds.txt"); // cant find file
InputSource input = new InputSource(fis);
xr.setContentHandler(this);
xr.parse(input);
What is the correct location to my file?
Use openFileInput to get FileInputStream object for those files which are written using openFileOutputStream
use the following code
FileInputStream fiss = openFileInput("myfeeds.txt");
InputSource input = new InputSource(fis);
xr.setContentHandler(this);
xr.parse(input);
You should use
openFileInput( String name )
to read your file.
Regards,
STéphane
Related
I have made a program that works perfectly well in java class.. but when I moved my code to a servlet it does not work as expected
the program creates some files writes to them then later reads from them.. the problem is when I move the code to servlet the program would not create files in the first place, so when later reading them it will give FileNotFound exception
this is how I create write to and read from files.
first, create file and write to it
...
Writer output = null;
File file = new File(i + ".txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
... then later read from file
File file = new File(i+".txt");
Scanner br = new Scanner(file);
// BufferedReader br = new BufferedReader(new FileReader(new File(TDM.class.getResource(i + ".txt").getPath())));
while (br.hasNextLine()) {
line = br.nextLine();
...
Notes:
*the above code is NOT in servlet.. servlet only CALL the method that contains this code.
*apparently, the PROBLEM is with creating the file.. for some reason the file is not created when the method is called from servlet. how ever it works perfectly when called from another java class.
thanks in advance
Use a path: File.createTempFile for temporary files, or convert a web path ("/.../...") relative to your web contents into a file system File:
File file =
request.getServletContext().getRealPath("/WEB-INF/files/" + i + ".txt");
file.getParentFile().mkdirs();
...
Better yet give URLs to a file, that will be delivered by a Servlet streaming the file to
response.setContentType("text/plain");
response.getOutputStream();
...
If you write resource "files," that may reside in a .war of .jar; then do not use File.
Read them using an InputStream:
InputStream in = getClass().getResource("/...").getResourceAsStream();
And copy them to the response.getOutputStream().
Also do not use the utility "short-hand" class FileWriter as it uses the platform encoding, which on Windows is some ANSI encoding and on Linux servers in general is UTF-8.
new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(file), "UTF-8"));
this comment from "Elliott Frisch" solved my problem
"You need to specify a path to your files."
simply I had to provide the "absolute" path instead of relative path
so, the code should be like this
Writer output = null;
File file = new File("/file/path/"i + ".txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
and
File file = new File("/file/path/"i+".txt");
Scanner br = new Scanner(file);
// BufferedReader br = new BufferedReader(new FileReader(new File(TDM.class.getResource(i + ".txt").getPath())));
while (br.hasNextLine()) {
line = br.nextLine();
then when I had this exception java.lang.NoClassDefFoundError: org/jsoup/Jsoup I just had to downlad the jsoup library from the internet and add it to my project under (library folder).
thank you very much for you all :)
I'm parsing a file. I'm creating a new output file and will have to add the 'byte[] data' to it. From there I will need to append many many other 'byte[] data's to the end of the file. I'm thinking I'll get the user to add a command line parameter for the output file name as I already have them providing the file name which we are parsing. That being said if the file name is not yet created in the system I feel I should generate one.
Now, I have no idea how to do this. My program is currently using DataInputStream to get and parse the file. Can I use DataOutputStream to append? If so I'm wondering how I would append to the file and not overwrite.
If so I'm wondering how I would append to the file and not overwrite.
That's easy - and you don't even need DataOutputStream. Just FileOutputStream is fine, using the constructor with an append parameter:
FileOutputStream output = new FileOutputStream("filename", true);
try {
output.write(data);
} finally {
output.close();
}
Or using Java 7's try-with-resources:
try (FileOutputStream output = new FileOutputStream("filename", true)) {
output.write(data);
}
If you do need DataOutputStream for some reason, you can just wrap a FileOutputStream opened in the same way.
Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);
This is for byte append. Don't forget about Exception
File file =new File("your-file");
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(your-string);
bufferWritter.close();
Of coruse put this in try - catch block.
Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}
Simple use,
FileUtils.copyFile()
you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();
How to Typecast File object into InputStream.
File file=new File("c:\\abc.txt");
Thanks
File file=new File("c:\\abc.txt");
InputStream is = new FileInputStream(file);
or
InputStream is = new FileInputStream("c:\\abc.txt");
You don't typecast the file to Input stream, you create an InputStream object using the file as parameter. You can use FileInputStream:
FileInputStream fis = new FileInputStream(file);
Use file as a parameter in a FileInputStream Object.
Like this,
FileInputStream fis = new FileInputStream(file);
Creates a FileInputStream by opening a connection to an actual file,
the file named by the File object file in the file system. A new
FileDescriptor object is created to represent this file connection.