I'm trying to create a simple recorder which gives 'pause' and 'resume' functionality to the user.
Since Android does not support this directly, I'm creating individual files whenever the user presses 'Pause' and 'Resume' with the suffixes _1, _2, so on.
I use the code below to concatenate them
public void mergeAllAndSave() {
// TODO Auto-generated method stub
Enumeration<FileInputStream> allRecordings;
Vector<FileInputStream> audiofiles = new Vector<FileInputStream>();
for (int i = 1; i < count+1; i++) {
try {
audiofiles.add(new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/"+ AUDIO_RECORDER_FOLDER + "/" + _filename + "_"+ i + file_exts[currentFormat]));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
allRecordings = audiofiles.elements();
SequenceInputStream siStream = new SequenceInputStream(allRecordings);
try {
FileOutputStream foStream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+ AUDIO_RECORDER_FOLDER + "/" + _filename + file_exts[currentFormat]);
int temp;
while ((temp = siStream.read() ) != -1) {
foStream.write(temp);
}
foStream.close();
siStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The code works fine. It gives me a single file. However it contains the contents of the first file only. Logcat does not show any errors, whatsoever.
Anyone with any ideas what is the mistake I am making?
Thanks.
Answer to this question is here.
PS: I cannot add this as a comment because I do not have sufficient reputation.
Related
I'm currently writing a program that will create a file and output as an integer how many times the code has been executed. this is my code:
import java.io.*;
public class Q1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count;
File file = new File("count.dat");
try {
FileOutputStream os = new FileOutputStream(file,true);
FileInputStream is = new FileInputStream(file);
if (is.available() == 0)
count = 0;
else
count = is.read();
count++;
//System.out.println(count);
os.write(count);
os.close();
is.close();
} catch (FileNotFoundException e) {
System.out.println("file not found");
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("IOException");
System.exit(0);
}
}
}
I've ran into a problem with the output, when I un-comment the sysout of count it has the correct number but when I run the program and view it with notepad++ it shows soh then for the second time it outputs the soh and stx. I don't understand where these outputs are coming, any help is appreciated.Thanks in advanced.
I've figured out that the output error was a problem with notepad but my file is getting overridden when I run the program.
I currently have a file download process in my java class, listed below, to take all the data in an SQL table and put it in a CSV file for user download. However, when I download the file, all the data is good except it will cut off at random points (usually around line 20 of the data, given there are at least over 100 lines of data). I want to ask, what if making the cutoff? Is it session time related or is the code just problematic?
public String processFileDownload() {
DataBaseBean ckear = new DataBaseBean();
ckear.clearContens();
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
Map<String, Object> m = fc.getExternalContext().getSessionMap();
dbase = (DbaseBean) m.get("dbaseBean");
message = (MessageBean) m.get("messageBean");
dataBean = (DataBean) m.get("dataBean");
dbmsUser = (DbmsUserBean) m.get("dbmsUserBean");
FileOutputStream fos = null;
String path = fc.getExternalContext().getRealPath("/temp");
String tableName = dbmsUser.getTableName();
String fileNameBase = tableName + ".csv";
java.net.URL check = getClass().getClassLoader().getResource(
"config.properties");
File check2 = new File(check.getPath());
path = check2.getParent();
String fileName = path + "/" + dbmsUser.getUserName() + "_"
+ fileNameBase;
File f = new File(fileName);
try {
f.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dbase.connect();
dbase.setQueryType("SELECT");
dbase.executeSQL("select * from " + tableName);
if (dbase.getResultSet() == null) {
FacesContext.getCurrentInstance().addMessage("myForm3:errmess",
new FacesMessage("Table doesn't exist!"));
return "failed";
}
Result result = ResultSupport.toResult(dbase.getResultSet());
downlaodedrows = result.getRowCount();
Object[][] sData = result.getRowsByIndex();
String columnNames[] = result.getColumnNames();
StringBuffer sb = new StringBuffer();
try {
fos = new FileOutputStream(fileName);
for (int i = 0; i < columnNames.length; i++) {
sb.append(columnNames[i].toString() + ",");
}
sb.append("\n");
fos.write(sb.toString().getBytes());
for (int i = 0; i < sData.length; i++) {
sb = new StringBuffer();
for (int j = 0; j < sData[0].length; j++) {
sb.append(sData[i][j].toString() + ",");
}
sb.append("\n");
fos.write(sb.toString().getBytes());
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String mimeType = ec.getMimeType(fileName);
FileInputStream in = null;
byte b;
ec.responseReset();
ec.setResponseContentType(mimeType);
ec.setResponseContentLength((int) f.length());
ec.setResponseHeader("Content-Disposition", "attachment; filename=\""
+ fileNameBase + "\"");
try {
in = new FileInputStream(f);
OutputStream output = ec.getResponseOutputStream();
while (true) {
b = (byte) in.read();
if (b < 0)
break;
output.write(b);
}
} catch (NullPointerException e) {
fc.responseComplete();
return "SUCCESS";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
fc.responseComplete();
return "SUCCESS";
}
The problem seems to be that you are simply appending commas between values and it's likely one of the values you are writing contains a delimiter, line separator or quote character, which will "break" the CSV format if not correctly escaped.
It would be way easier and faster to use CSV library for that. uniVocity-parsers comes with pre-built routines to dump your resultset into properly formatted CSV. In your case, you could use this library in the following manner:
ResultSet resultSet = dbase.getResultSet();
// Configure the output format as needed before actually dumping the data:
CsvWriterSettings writerSettings = new CsvWriterSettings(); //many settings here, check the tutorials & examples.
writerSettings.getFormat().setLineSeparator("\n");
writerSettings.setHeaderWritingEnabled(true); // we want the column names to be printed out as well.
// Then create a routines object:
CsvRoutines routines = new CsvRoutines(writerSettings);
// The write() method takes care of everything. The resultSet and any other resources required are closed by the routine.
routines.write(resultSet, new File(fileName), "UTF-8");
Hope this helps
Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0. license)
Hi everyone i am practicing with java data input output stream. But i don't know how to fix this problem i can write data input stream to my file but can't read it
here is my code:
public static void readDataIOStream(){
DataInputStream dataIn = null;
int i = 10;
double d = 1023.56;
boolean b = true;
try {
dataIn = new DataInputStream(
new FileInputStream("test.txt"));
i = dataIn.readInt();
System.out.println("Reading " + i);
d = dataIn.readDouble();
System.out.println("Reading " + d);
b = dataIn.readBoolean();
System.out.println("Reading " + b);
d = dataIn.readDouble();
System.out.println("Reading " + d);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}try {
dataIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void writeDataIOStream(){
DataOutputStream dataOut = null;
int i = 10;
double d = 1023.56;
boolean b = true;
try {
dataOut = new DataOutputStream(new FileOutputStream("test.txt"));
System.out.println("Writing " + i);
dataOut.write(i);
System.out.println("Writing " + d);
dataOut.writeDouble(d);
System.out.println("Writing " + b);
dataOut.writeBoolean(b);
System.out.println("Writing " + 12.2 * 7.4);
dataOut.writeDouble(12.2 * 7.4);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
dataOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is error :
java.io.EOFException
at java.io.DataInputStream.readFully(Unknown Source)
at java.io.DataInputStream.readLong(Unknown Source)
at java.io.DataInputStream.readDouble(Unknown Source)
at bytestream.DataIOStream.readDataIOStream(DataIOStream.java:108)
at bytestream.DataIOStream.main(DataIOStream.java:16)
Writing 10
Writing 1023.56
Writing true
Writing 90.28
Reading 172003324
Reading 8.029891292620447E283
Reading true
Please help me why i can't read Data Input stream
dataOut.write(i) only writes one byte. Yet you are reading an int doing i = dataIn.readInt() which is 4 bytes.
Therefore when trying to read the last element which is a double, there is only 5 bytes in the stream while it is trying to read 8 bytes (the length of a double), hence the exception.
Since you want to write/read an int, you need to call dataOut.writeInt(i) instead of dataOut.write(i).
I am making an app that gets data from SOAP. When it has the data it must put it in a listview.
the result string is:
it_id=636207115 :#=1:price=1,18|it_id=636207115 :#=1:price=1,18|it_id=636205395 :#=1:price=0,92
I now have to split the string like this: it_id=636207115 :#=1:price=1,18 , as you can see the string splits at the '| '.
But now i have to split the string again to get three strings from that. But i cant figure out how to split it then. I need to split that string at the ':' and put it then in the listview.
If anyone knows how to split split the string please let me know!
First Encode your String and then use spilt() and than Decode String to Original
try {
str = URLEncoder.encode("t_id=636207115 :#=1:price=1,18|it_id=636207115 :#=1:price=1,18|it_id=636205395 :#=1:price=0,92", "UTF-8");
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String abc[] = str.split("%7C"); // %7C is Encoded | by which you want to spilt the String
// Loop Through the Array and Decode the String !
for (int i = 0; i < abc.length; i++) {
try {
abc[i] = URLDecoder.decode(abc[i], "UTF-8");// Decoding String and Stroring it back to Array
System.out.println(abc[i]);// Testing String
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String selectedFromList = text.getText().toString();
String abc[] = selectedFromList.split(","); // %7C is Encoded | by which you want to spilt the String
for (int i = 0; i < abc.length; i++) {
try {
if(i==abc.length-1)
Log.i("deepika deepika ::", abc[i]);
tvCountryName.setText(abc[i]);
edit.putString(COUNTRY, abc[i]);
edit.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String selectedFromList = "hello, hi, how are you, guys";
String abc[] = selectedFromList.split(",");
for (int i = 0; i < abc.length; i++) {
try {
Log.i("deepika deepika ::", abc[i]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have struggled a long time to get the try-catch-finally block to work. I'm a beginner in java, and are currently learning how to read/write/handle exceptions. In my task I'm trying to read from two separate .txt files. One has countries and population, the other has countries and the area of the country. This is further printed out to a new file where information about countries and area per person is displayed.
I'm not sure if I really can put the finally inside a try-catch block.
Currently I'm getting the error message "Unhandled FileNotFoundException etc.". I've been trying this for for a long time now, and just can't get it to work properly.
private String country;
private double value;
Scanner in1 = new Scanner(new File("countryPopulation.txt"));
Scanner in2 = new Scanner(new File("countryArea.txt"));
PrintWriter out = new PrintWriter("countryAreaPerInhabitant");
public IOAndExceptionHandling(String line) {
int i = 0;
while (!Character.isDigit(line.charAt(i))) {
i++;
}
this.country = line.substring(0, i - 1).trim();
this.value = Double.parseDouble(line.substring(i).trim());
}
public String getCountry() {
return this.country;
}
public double getValue() {
return this.value;
}
public void printAreaPerPerson() {
try {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
}
finally {
in1.close();
in2.close();
out.close();
}
}
catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
}
catch (IOException e) {
e.printStackTrace();
}
}
Thanks! :)
The finally block goes after the catch blocks. It will execute regardless of an exception being thrown or successful completion of the block.
Scanner in1; //field declaration with no assignment
Scanner in2; //field declaration with no assignmetn
/* Omitted Class declaration & other code */
try {
in1 = new Scanner(new File("countryPopulation.txt")); //these require FNF to be caught
in2 = new Scanner(new File("countryArea.txt"));
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(
in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(
in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
} catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
} catch (IOException e) {
e.printStackTrace();
} finally {
in1.close();
in2.close();
out.close();
}
The first rendition of this code was throwing the unhandled exception error because the inner try block did not catch the FileNotFoundException. Even though you had a try...catch wrapping that try block, which did catch the FileNotFoundException, the exception would not propogate upwards through the nested try..catch statements
You are nesting two try catch blocks. The inner one only has try finally, but no catch statements. That's where the FileNotFoundException would occur.
try {
try {
Either remove the outer block and just use one or move the catch statements inside the inner try finally.
Copy paste this
public void printAreaPerPerson() {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
} catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
} catch (IOException e) {
e.printStackTrace();
} finally {
in1.close();
in2.close();
out.close();
}
}
Put the finally block out side of your try block.
You don't need the inner try block.