2
我寫了一個代碼,通過將其轉換爲字符串並將其發送到Web服務來發送文本文件。請有人告訴我其他可用的方法將字符串作爲流發送到Web服務。將文本文件轉換爲java中的字符串
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;
}
}
你應該使用StringBuilder而不是字符串連接內部循環。 – msell
我正在接受一個文本文件並將其發送到Web服務,因此它發送這樣的值 –
文件編碼是當前平臺的文件編碼;像你一樣,更好地使用'InputStreamReader(FileInputStream,「UTF-8」)''。另外'編碼+ =行+「\ n」;'左右,因爲readLine剝離行結束。如果可能,更好地使用Apache Commons io [FileUtils.readFileToString](http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html)。 –