2012-11-21 59 views
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; 
    } 

} 

回答

3

從文件中讀取數據,並把它轉換爲字符串,並提前做好你的進程試試這個。

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

使用此代碼根據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) { 

     } 
+6

你應該使用StringBuilder而不是字符串連接內部循環。 – msell

+0

我正在接受一個文本文件並將其發送到Web服務,因此它發送這樣的值 –

+1

文件編碼是當前平臺的文件編碼;像你一樣,更好地使用'InputStreamReader(FileInputStream,「UTF-8」)''。另外'編碼+ =行+「\ n」;'左右,因爲readLine剝離行結束。如果可能,更好地使用Apache Commons io [FileUtils.readFileToString](http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html)。 –

相關問題