I'm using java SE eclipse.
As I know, When there are no file named by parameter FileOutputStream constructor create new file named by parameter. However, with proceeding I see that FileOutputStream make exception FileNotFoundException. I really don't know Why this exception needed. Anything wrong with my knowledge?
My code is following(make WorkBook and write into file. In this code, although there are no file "data.xlsx", FileOutpuStream make file "data.xlsx".
public ExcelData() {
try {
fileIn = new FileInputStream("data.xlsx");
try {
wb = WorkbookFactory.create(fileIn);
sheet1 = wb.getSheet(Constant.SHEET1_NAME);
sheet2 = wb.getSheet(Constant.SHEET2_NAME);
} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
e.printStackTrace();
} // if there is file, copy data into workbook
} catch (FileNotFoundException e1) {
initWb();
try {
fileOut = new FileOutputStream("data.xlsx");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // if there is not file, create init workbook
} // ExcelData()
If anything weird, please let me know, thank you
It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. To be sure you probably should first test that the file exists before you create the FileOutputStream (and create with createNewFile() if it doesn't)
File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false);
Answer from here: Java FileOutputStream Create File if not exists
There is another case, where new FileOutputStream("...") throws a FileNotFoundException, i.e. on Windows, when the file is existing, but file attribute hidden is set.
Here, there is no way out, but resetting the hidden attribute before opening the file stream, like
Files.setAttribute(yourFile.toPath(), "dos:hidden", false);
Related
I have created a file and I want to write in bytes in this file but it's not working. Where is the problem?
public void writeFileExternalStorage() {
File file = new File(getExternalFilesDir(null), "hhh.txt");
try {
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream ;
outputStream = new FileOutputStream(file, true);
outputStream.write(files.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The createNewFile call will return true if it has successfully created the file. You should check the result of the call, and log an error if it is false.
According to the documentation for getExternalFilesDir (javadoc):
[it m]ay return null if shared storage is not currently available.
If that happens you will call new File(null, "hhh.txt"). That is equivalent to new File("hhh.txt") (javadoc), so the file would be created in the app's "current user directory".
I have a problem saving a file in android, the FileOutputStream keeps falling back to a FileNotFoundException and thus won't write the file to the external storage.
Yes I do have permission set in the manifest:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I've added the code below of the function, can someone explain to me what is going wrong, if it is that it is trying to overwrite an existing file, is there a way to replace that file (the name needs to be static)?
(tips on making the code look nicer are welcome as well)
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files");
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdir();
}
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Kudos to Guillaume and theV0ID for leading me to the most efficient correct answer.
Below is the example code editted to the working version.
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
pictureFile.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Try this :
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+ File.separator + "Tempsave.png");
pictureFile.getParentFile().mkdirs();
You need to create the file directories if they don't exist. If not the FileOutputStream will throw a FileNotFoundException
I have the below 2 methods, supposed to read and write to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
#SuppressWarnings("unused")
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
When I'm calling the above methods I'm getting this error:
02-15 10:28:48.165: E/log activity(1743): Can not read file: java.io.FileNotFoundException: /jokesBody1.bjk: open failed: ENOENT (No such file or directory)
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
File file = new File("jokesBody1.bjk");
Why I'm getting this error? I know that I'm missing something small - probably a piece of code that creates the file(I'm not sure), but as a beginner, I'm not able to spot the issue.
File file = new File("jokesBody1.bjk");
Just creates a File objects that points to that path, but no actual file.
Use
file.createNewFile();
To actually create the file.
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
Actually, no. It only creates a File object, an then java assumes that file to exist.
Well, first of all, I'm just learning and don't quite understand what I'm doing.
What I want is to create an Excel file in memory and then it would be possible to send it with ActionBarSherlock's ShareActionProvider to mail for example.
But I got exeption :
11-24 18:45:52.112: W/System.err(22073): java.io.FileNotFoundException: /Competition.xls: open failed: EROFS (Read-only file system)
As I searched for the answer on the web - it's the problem of file being created in the system area which is read-only. But I want to create it in memory.. Somehow. Once again, I don't really understand well how it works - the way I see it - I create .xls file somewhere in the memory. So the explanation would be helpful.
So, here's the code :
private void createFileTosend() {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend=null;
try {
toSend = getFile();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream = new BufferedInputStream(new FileInputStream(toSend));
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
public File getFile() throws IOException, WriteException{
File file=new File("Competition.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
//then goes creation of Excel 's xls file which is not important for the question
workbook.write();
workbook.close();
return file;
}
Once again, don't downvote me, please, I'm just learning
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ass per the error log you post, i guess you didn't read it carefully. IT is saying read only file system. You need to put the above permission ATLEAST in your android manifest.
Do this much and see if there is any more error or not
I have a doubt may be wrong
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
you are using Context.MODE_WORLD_READABLE its readable, so how can you access it in write mode later. Is it right?
Check this link
Use the http://developer.android.com/guide/topics/data/data-storage.html to clear your doubt about file creation
My requirement is that I should read a template file and change some values in its content and write it back to another file. Most importantly it should have the same styles as that of the template.
The problem I face is that I am able to read and write, but its very difficult to transfer the styles as well. Especially I am tired trying to apply the paragraph styles to the document. Pls help me..... this is my code
public static void main(String[] args) {
try {
HWPFDocument templateFile = new HWPFDocument(new FileInputStream("D:\\POI\\testPOIin.doc"));
HWPFDocument blankFile = new HWPFDocument(new FileInputStream("D:\\POI\\blank.doc"));
ParagraphProperties pp = templateFile.getRange().getParagraph(4).cloneProperties();
blankFile.getRange().insertAfter(pp, 0);
OutputStream out = new FileOutputStream("D:\\POI\\testPOIout.doc");
blankFile.write(out);
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (Exception ioe) {
// TODO: Add catch code
ioe.printStackTrace();
}
}
}
Pls let me know that I am doing wrong.....
I also had similar task and after investigation i created solution, but it works only for docx files:
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream(new File("transformed.docx"));
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("original.docx")));
for(XWPFParagraph p:doc.getParagraphs()){
for(XWPFRun r:p.getRuns()){
for(CTText ct:r.getCTR().getTList()){
String str = ct.getStringValue();
if(str.contains("NAME")){
str = str.replace("NAME", "Java Dev");
ct.setStringValue(str);
}
}
}
}
doc.write(fos);
}
it operates on low level elements so it saves styles and other props. Hope it will help somebody.