2012-11-21 54 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)。 –

相关问题