I'm trying to save int values inside a text file on external storage. When I tried to use the saveAudio() function, I get a FileNotFoundException. What am I doing wrong? I'm running the program in an android emulator.
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsoluteFile(),"audiosettings.txt");
/**Stores the game volume level*/
int gameVolume_level;
/**Stores the music volume level*/
int musicVolume_level;
/**Stores the GUI volume level*/
int guiVolume_level;
private void loadAudio() {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(externalStorageDir));
gameVolume_level = dis.readInt();
dis.readChar();
musicVolume_level = dis.readInt();
dis.readChar();
guiVolume_level = dis.readInt();
dis.readChar();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void saveAudio() {
DataOutputStream dos;
try {
dos = new DataOutputStream(new FileOutputStream(externalStorageDir));
dos.writeInt(gameVolume_level);
dos.writeChar('\t');
dos.writeInt(musicVolume_level);
dos.writeChar('\t');
dos.writeInt(guiVolume_level);
dos.writeChar('\n');
dos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your implementation is right. But notice that you have to verify that a SD card is available on your phone or emulator.
To make it easier, you can try whether
Environment.getExternalStorageDirectory().getAbsoluteFile()
returns existing file.
If the file exists, check the permission. Following permission is needed in AndroidManifest.xml, if you want to use external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it helps.
Related
I want to know how can I use java to confirm a file is a picture file.
I have tried the following code:
public static void main(String[] args) {
// get image format in a file
File file = new File("C:/Users/dell、/Desktop/4.xlsx");
// create an image input stream from the specified fileDD
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
System.out.println("Not a picture file");
throw new RuntimeException("No readers found! Unable to read the uploaded file");
}
// get the first reader
ImageReader reader = iter.next();
try {
System.out.println("Format: " + reader.getFormatName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close stream
if (iis != null){
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But it doesn't work perfectly! It shows an exception once the file is not a picture file, so I want to find a better way.
There are too many image extensions. Maybe the best way to validate if a file is an image, is using Regular Expressions. Something like this...
([^\s]+(\.(?i)(jpg|png|gif|bmp|MORE|IMAGE|EXTENSIONS))$)
Here is a complete example of the implementation.
Use ImageIO#read.
public static boolean isPictureFile(File file){
try{
return ImageIO.read(file) != null;
}catch(Exception ex){
return false;
}
}
Basically, the method ImageIO.read(File) will return a BufferedImage object when it successfully read the image file, a null otherwise. All we have to do is to let ImageIO read the file and check if it returns a null or not, and if there it throws an exception for whatever reason, we can safely assume the file is not a picture file.
I'm trying to modify a doc with Apache POI in Java.
At first the test.doc cannot be read with a exception raised up :
"org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x6576206C6D783F3C, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
"
So I saved the doc as "word 97 - 03" format,and then POI can read the doc properly.
But when I try to rewrite the content to a new file with nothing changed, the file output.doc cannot be opened by MS Office.
When I make a new doc myself with MS Office, the POI works well, everything goes right.
So the problem is "test.doc".
The test.doc is generated by some sort of a program which I can't access the code,so I don't know what goes wrong.
My question is :
1.As test.doc can be read by MS Office why can't POI without saving as a new format doc?
2.As the POI can read the doc, why it cannot write back to a new file(MS Office can't open)?
Here is my code:
FileInputStream fis = null;
try {
fis = new FileInputStream("test.doc");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
POIFSFileSystem pfs = null;
try {
pfs = new POIFSFileSystem(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HWPFDocument hwdf = null;
try {
hwdf = new HWPFDocument(pfs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("output.doc"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
hwdf.write(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
pfs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The HEX stuff read as ASCII and read little-endian converts to <?xml ve, which indicates that test.doc is some other format than actually .doc/.docx.
Word will open other data-formats gracefully sometimes, upon saving it will be saved correctly in the Word-Format.
Therefore you will need to use a hex-editor to take a look at the contents of test.doc and if it is really in some broken format you need to find out where it is coming from and how the creation of that file can be fixed.
I am trying to convert large 3gp file(>than 25mb) to byte array but it gives outofmemory exception.i am able to convert less than 25 mb 3gp file to bytearray.
File file1 = new File (Environment.getExternalStorageDirectory() + "1.3gp");
FileInputStream fis = null;
try {
fis = new FileInputStream(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while (fis.available() > 0) {
bos.write(fis.read());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] bytes = bos.toByteArray();
File someFile = new File (Environment.getExternalStorageDirectory()+ "/output.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(someFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
////
how to convert the large 3gp file into bytearray.
give a proper example or method.
Set the -Xmx option on the virtual machine being used to run the program to a larger value to give it more memory to work with.
You can do that as a command line option if running the program directly, or as a setting on the project in your IDE if running it from an IDE.
I am getting the occassional error message when I try to read a serialized object from a file. It works fine 9 times out of 10, but for some reason I get lots of these error message sin the catlog:
06-01 23:57:50.824: ERROR/MemoryFile(16077): MemoryFile.finalize() called while ashmem
still open
and
06-01 23:57:57.664: ERROR/MemoryFile(16077): java.io.IOException: munmap failed
The second message comes with no indication where the exception is caused. (Clearly when I'm loading the file, but I already have a try/catch around it.)
My loadfile method looks like this:
public TGame loadSavedGame(){
TGame g=null;
InputStream instream = null;
BufferedReader br=null;
InputStreamReader inputreader=null;
try {
File sdCard = Environment.getExternalStorageDirectory();
instream = new
FileInputStream(sdCard.getAbsolutePath()+"/egyptica/serializationtest");
// inputreader = new InputStreamReader(instream);
// br= new BufferedReader(inputreader);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return g;
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT
FOUND):"+ex.getMessage(), "ex");
ex.printStackTrace();
return null;
}
} catch (StreamCorruptedException ex) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+ex.getMessage(),
"ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
} catch (IOException ex) {
android.util.Log.e("DESERIALIZATION FAILED (IO
EXCEPTION):"+ex.getMessage(), "ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
}
}
One possibility I have thought of is using a BufferedReader to rea the file. However I'm not sure how to go about doing this. Any help would be appreciated.
Try to put finally block after try and put there closing statements for your streams and also useful thing is to use:
FileInputStream.getFD().sync();
It makes sure that file really received your close/flush
I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}