Convert large 3gp files into byte array - java

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.

Related

InvocationTargetException for ClassLoaders.callStaticFunction Java Eclipse

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

read a doc and rewrite with Apache POI ,but fail to open with office

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.

Java - Apache POI - Read/Write .xlsx file - File getting corrupted and becomes empty

I am using a Java program to read and write an existing .xlsx file(same file) but the file is getting corrupted, and the file size becomes zero bytes which is causing "org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)”.
One more thing is - this is not happening consistently. The program is reading and writing to file properly most of the time but occurring once out of 10-15 runs. It would be helpful if anyone has a solution to this. BTW, am using Apache POI 3.13.
Read File Program:
public String getExcelData(String sheetName, int rowNum, int colNum){
String retVal = null;
try {
FileInputStream fis = new FileInputStream("/Absolute/File/Path/Test-File.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(sheetName);
Row r = s.getRow(rowNum);
Cell c = r.getCell(colNum);
retVal=(c.getStringCellValue());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal;
Write File Program :
public void writeToExcel(String sheetName,int rowNum,int cellNum,String desc){
try {
FileInputStream fis = new FileInputStream("/Absolute/File/Path/Test-File.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(sheetName);
Row r = s.getRow(rowNum);
Cell c = r.createCell(cellNum);
c.setCellValue(desc);
FileOutputStream fos = new FileOutputStream("/Absolute/File/Path/Test-File.xlsx");
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Error Trace:
Exception in thread "main" org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
at org.apache.poi.util.IOUtils.peekFirst8Bytes(IOUtils.java:55)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:201)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:168)
at ExcelLibrary.getExcelData(ExcelLibrary.java:139)
at Driver.main(Driver.java:82)
You are reading and writing to the same file at the same time. Try to first close FileInputStream fis before writing to FileOutputStream fos.
Or use temporary file to write new result and then rename it to original one.
BTW. close automatically performs flush, so it don't has to be called separately.
you need to close the FileInputStream and FileOutputStream with org.apache.commons.io.IOUtils.closeQuietly(fos) and fis.
When you write to your file, you seem not to be using flush. Furthermore, your close code should be done in a finally block to ensure the stream is closed even if something wrong happens.
As a java dev, you need to use finally block when you use try-catch block.
in your finally block, you must close FileInputStream and FileOutputStream.may be filehandler opened as you didn't close.
I faced this issue initially, solution is simple.
I am writting only code line which u need to add fis.close();
wb.close(); before returning retval
public String getExcelData(String sheetName, int rowNum, int colNum){
String retVal = null;
try {
FileInputStream fis = new FileInputStream("/Absolute/File/Path/Test-File.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(sheetName);
Row r = s.getRow(rowNum);
Cell c = r.getCell(colNum);
retVal=(c.getStringCellValue());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fis.close();
wb.close();
return retVal;
}
Try this one out. I was facing the same issue but resolved it with below.
FileInputStream fis=new FileInputStream(-Location-);
--- do whatever you want to do --
fis.close();
FileOutputStream fos=new FileOutputStream(-Location-);
wb.write(fos);
fos.close();
wb.close();

Saving a string Android

I'm trying to save a url as a string so that I can use it in another part of my app but its not working properly. Here's what I have.
Saving
String FILENAME = "usertimetable";
String string = mWebView.getOriginalUrl();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Opening
FileInputStream fis = null;
try {
fis = openFileInput("usertimetable");
url = fis.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try using the read() method, rather than toString().
(http://developer.android.com/reference/java/io/FileInputStream.html for more info.)

Extracting a file with JUnrar

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();
}
}
}
}

Categories

Resources