2

i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.

public class MainActivity extends Activity { Button b1; String s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { File upfile=new File("sdcard/text/testfile.txt"); try { FileInputStream fin=new FileInputStream(upfile); byte[] buffer= new byte[(int)upfile.length()]; new DataInputStream(fin).readFully(buffer); fin.close(); s=new String(buffer,"UTF-8"); System.out.print(buffer); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub Toast.makeText(MainActivity.this, s, 20).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } 

2 Answers 2

4

try this.

public void mReadJsonData() { try { File f = new File("sdcard/text/testfile.txt"); FileInputStream is = new FileInputStream(f); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String text = new String(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

Use this code to read the data from file and get it into string and do your process ahead according to your need--

File upfile=new File("sdcard/text/testfile.txt"); try { final BufferedReader reader = new BufferedReader(new FileReader(upfile)); String encoded = ""; try { String line; while ((line = reader.readLine()) != null) { encoded += line; } } finally { reader.close(); } System.out.print(encoded); } catch (final Exception e) { } 

3 Comments

You should use StringBuilder instead of string concatenation inside loops.
I am taking a text file and sending it to web service,Hence is it fine send the value like this
The file encoding is that of the current platform; better use, as you did, an InputStreamReader(FileInputStream, "UTF-8"). Also encoded += line + "\n"; or so, as readLine strips the line ending. Better use from Apache commons io FileUtils.readFileToString if possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.