在java中将文本文件转换为字符串

时间:2012-11-21 07:29:28

标签: java android

我有一个代码,用于通过将文本文件转换为字符串并将其发送到Web服务来发送文本文件。请有人告诉我其他可用的方法将字符串作为流发送到Web服务。

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 个答案:

答案 0 :(得分:4)

试试这个。

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();
    }
}

答案 1 :(得分:0)

使用此代码从文件中读取数据并将其转换为字符串,并根据您的需要提前完成您的流程 -

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) {

        }