Android : Writing part of text file to another file - android

I have a multipart format text file. i am going threw the file looking for start of content and from then on writing the content to another file until i hit end of content.
FileInputStream in = new FileInputStream(getContentPath());
InputStreamReader sr = new InputStreamReader(in, "UTF-8");
BufferedReader buffreader = new BufferedReader(sr);
String lineStr;
while ((lineStr = buffreader.readLine()) != null) {
if (lineStr == "") {
FileOutputStream fos = new FileOutputStream("", true);
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write(lineStr);
fbw.newLine();
fbw.flush();
fbw.close();
}
}
The problem i am getting is the resulting files encoding is all messed up. The input is utf8.
Original in multipart format
Just image file extracted(funny-pictures-bomb-squad-cat-chooses-the-blue-wire.jpg)

Found problem the input charset was not utf8 it is iso-8859-1 http default.
Used CharsetDecoder to make sure i read/saved string as iso-8859-1.

FileWriter writer = new FileWriter(highscoresFile, true);
The boolean at the end tells you whether or not to append to the end of the file.

Related

While reading data from a stream, why does my program hang?

While reading data from a stream I am writing to a newly created temporary XML file. But the program hangs.
What have I missed here?
if (deviceSocket.isConnected()) {
OutputStream os = deviceSocket.getOutputStream();
os.write(xmlStr.getBytes());
os.flush();
// Read Response from Socket
respFromDevice = new BufferedReader(new InputStreamReader(deviceSocket.getInputStream()));
FileWriter fileWriter = null;
// Write into temp xml file
String response;
while ((response = respFromDevice.readLine()) != null) {
sb.append(response);
File newTextFile = new File("tmp.xml");
fileWriter = new FileWriter(newTextFile);
fileWriter.write(sb.toString());
//Files.write(Paths.get("temp.xml"), sb.toString().getBytes());
System.out.println(response);
}
}

What encoding can be used to send the binary data to PHP?

I am trying to send some binary data that is stored on the Android phone as a file to the web service that is created in PHP.
I have tried using MultiPart as well as ValuePair but no luck..!!
What I also did is to create a console application in Java, which reads the binary file from a static location on Windows and use the same PHP service and it works fine using MultiPart, below is the code for that:
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file,"text/plain");
mpEntity.addPart("qLog", new StringBody(readFileAsString(file.getAbsolutePath()),
Charset.defaultcharset)));
mpEntity.addPart("fileName", new StringBody(fileName));
mpEntity.addPart("personid", new StringBody(userid));
and the function readFileAsString() is:
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while ((numRead=reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
But when I do this on Android it is not maintaining the binary values. The reason I think is due to the default encoding in Android is UTF-8.
Can you please help here? How do I get the binary data sent from Android to PHP Service?
You can use InputStreamBody instead of StringBody:
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("qLog", new InputStreamBody(new FileInputStream(file),
file.getName());
mpEntity.addPart("fileName", new StringBody(fileName));
mpEntity.addPart("personid", new StringBody(userid));
Edited
Or you can use FileBody for more concise.

file saving on android

I am making a xml file and saving it on my device code follows
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx:xx:xx:xx:yy/LoginAndroid.asmx/login");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
//Toast.makeText( getApplicationContext(),"responseBody: "+responseBody,Toast.LENGTH_SHORT).show();
//saving the file as a xml
FileOutputStream fOut = openFileOutput("loginData.xml",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(responseBody);
osw.flush();
osw.close();
//reading the file as xml
FileInputStream fIn = openFileInput("loginData.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[responseBody.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
FIle is saving I can also read the file every thing is ok but look at this line
char[] inputBuffer = new char[responseBody.length()];
it is calculating string length which is saved at the time of Saving the file.I am saving the file in one Acivity and reading it from another activity and my application will save the file locally once so I could not be able to get the length of that return string every time So is there any way to allocate the size of char[] inputBuffer dynamically?
you can use the below code in your another activity to read the file. Have a look at BufferedReader class.
InputStream instream = new FileInputStream("loginData.xml");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (buffreader.hasNext()) {
line = buffreader.readLine();
// do something with the line
}
}
Edit:
The above code is working fine for reading a file, but if you just want to allocate the size of char[] inputBuffer dynamicall then you can use the below code.
InputStream is = mContext.openFileInput("loginData.xml");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] inputBuffer = bos.toByteArray();
Now , make use inputBuffer as you want.

android add filename to bytestream

im trying to send a file in android through sockets. i want to add the filename with the bytestream and then send it to the server. how do i do that? and then how do i seperate the filename on the receiving side?
this is the code to send file :
Log.i("SocketOP", "sendFILE-1");
File f = new File(path);
String filename=path.substring(path.lastIndexOf("/")+1);
System.out.println("filename:"+filename);
fin.filename = "~"+filename;
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [(int)f.length()];
System.out.println("SO sendFile f.length();" + f.length());
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, buffer.length);
System.out.println("SO sendFile" + bytesRead +filename);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
If this is your own protocol then you create a data packet that separate the two sections (filename and data). You need to denote clearly the separation via a particular boundary.
On the server, since you understand the protocol, the server will read back the whole data packet and it will separate the filename and data based on the given boundary.
MIME data format use exactly this kind of data exchange and widely use with HTTP protocol. If you use the same MIME Data Format, another advantage is you could use third party library to encode and decode your data such as HttpMime
Below is the rough code to format the data using MIME data and send it through Socket
File f = new File(path);
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
String filename=path.substring(path.lastIndexOf("/")+1);
// create a multipart message
MultipartEntity multipartContent = new MultipartEntity();
// send the file inputstream as data
InputStreamBody isb = new InputStreamBody(new FileInputStream(f), "image/jpeg", filename);
// add key value pair. The key "imageFile" is arbitrary
multipartContent.addPart("imageFile", isb);
multipartContent.writeTo(out);
out.flush();
out.close();
Note that you would need org.apache.http.entity.mime.MultipartEntity and org.apache.http.entity.mime.content.InputStreamBody from HttpMime project. On the server, you need MIME parser that would get back the filename and all the bytes content
To read the inputstream back on the server, you would need a class to parse the MIME message. You shouldn't have to write the parser yourself as MIME is a popular message format already unless you want to learn about the MIME message structure.
Below is the sample code using MimeBodyPart that is part of JavaMail.
MimeMultipart multiPartMessage = new MimeMultipart(new DataSource() {
#Override
public String getContentType() {
// this could be anything need be, this is just my test case and illustration
return "image/jpeg";
}
#Override
public InputStream getInputStream() throws IOException {
// socket is the socket that you get from Socket.accept()
BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
return inputStream;
}
#Override
public String getName() {
return "socketDataSource";
}
#Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
});
// get the first body of the multipart message
BodyPart bodyPart = multiPartMessage.getBodyPart(0);
// get the filename back from the message
String filename = bodyPart.getFileName();
// get the inputstream back
InputStream bodyInputStream = bodyPart.getInputStream();
// do what you need to do here....
You could download JavaMail from Oracle Website which also has dependency on Java Activation Framework

Problems reading text from file

I'm trying to read some text from a .txt file, here's my code:
String filePath = bundle.getString("filepath");
StringBuilder st = new StringBuilder();
try {
File sd = Environment.getExternalStorageDirectory();
File f = new File(sd, filePath);
FileInputStream fileis = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(
fileis));
String line = new String();
while ((line = buf.readLine()) != null) {
st.append(line);
st.append('\n');
}
Log.i("egor", "reading finished, line is " + line);
} catch (FileNotFoundException e) {
Log.i("egor", "file not found");
} catch (IOException e) {
Log.i("egor", "io exception");
}
reader.setText(st.toString());
The text looks like this:
This is a sample text to test
The .txt file is created in Windows notepad.
And here's what I'm getting:
What's wrong with my code? Thanks in advance.
Is the file in utf-8 (unicode) format? For some reason, Notepad always adds a byte-order mark to unicode files, even when the byte-order is irrelevant. When interpreted as ASCII or ANSI, the BOM will be seen as several characters. It's possible this is what's causing your problem.
If so, the solution is to use a more competent text editor than Notepad, or write code that checks for a BOM first in all unicode files.
If none of this makes sense to you, try googling 'unicode' and 'byte-order mark'.
Wrap a FileReader object in the BufferedReader object instead.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
st.append(line);
st.append("\n");
}
br.close();
Try with the folowing code
File f = new File(str);
FileInputStream fis = new FileInputStream(f);
byte[] mydata1 = new byte[(int) f.length()];
fis.read(mydata1);
System.out.println("...data present in 11file..."+new String(mydata1));

Categories

Resources