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)。 –