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.
Related
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);
}
}
I am trying to read InputStream after writing output stream to sdcard. I have downloaded file from HttpURLConnection. File is successfuly written to sdcard. But I am trying to read inputstream from same file but contents are not being read properly. On emulator some contents are shown but on actual device contents are not shown. Can you please help what can be the issue? I am posting downloading, writing and reading code.
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
InputStream is = connection.getInputStream();
/**
* Create file with input stream
*/
File downloadFile = new File("/sdcard/", "myFile3.pdf");
downloadFile.createNewFile();
final FileOutputStream outputStream = new FileOutputStream(downloadFile);
int availbleLength = is.available();
byte[] bytes = new byte[availbleLength];
int len1 = 0;
while ((len1 = is.read(bytes)) > 0) {
outputStream.write(bytes, 0, len1);
}
outputStream.flush();
outputStream.close();
File myFile = new File("/sdcard/myFile3.pdf");
InputStream inputStream = new FileInputStream(myFile);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
System.out.println("Byte Lenght: " + buffer.length);
inputStream.available() is only an estimate not actual length of the complete input data.
FileInputStream.available()
How do you save an entity to SDCard, in a streamed manner (To avoid memory issues).
I cant find any solid documentation on the matter.
response = httpClient.execute(request);
BufferedHttpEntity responseEntity = new BufferedHttpEntity(response.getEntity());
FileOutputStream fos = new FileOutputStream(Files.SDCARD + savePath);
responseEntity.writeTo(fos);
fos.flush();
fos.close();
This gives me the file, but with no contents. (2KB in size). So its not writing properly.
The server is sending a FileStream. Which I have confirmed to work.
I would try this approach:
HttpResponse response = httpClient.execute(post);
InputStream input = response.getEntity().getContent();
OutputStream output = new FileOutputStream("path/to/file");
int read = 0;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
output.close();
Hope it helps.
Cheers.
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.
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));