【问题标题】:why stringbuffer doesnt work in this code? [closed]为什么 stringbuffer 在这段代码中不起作用? [关闭]
【发布时间】:2014-05-08 19:34:01
【问题描述】:

我要xml.file

第一:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Text1" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="36dp"
        android:text="Button1" />



</RelativeLayout>

秒:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="20dp"
        android:layout_marginTop="28dp"
        android:text="TextView" />

</RelativeLayout> 

我在资产文件夹中有一个 txt.file,其名称为 12.txt 我想当我在第一个 xml.file 中按下 button1 时,我会转到第二个 xml.file 和 textview,并在资产文件夹中设置我的 txt.file

代码是:

public class Text2 extends Activity {
private TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text2);
        txt=(TextView)findViewById(R.id.textView1);


        FileInputStream fis=null;
        final StringBuffer buffer= new StringBuffer();

        try {
            fis = openFileInput("12.txt");
            DataInputStream dataIO = new DataInputStream(fis);
            String strLine = null;

            if ((strLine = dataIO.readLine()) != null) {
                buffer.append(strLine);
            }

            dataIO.close();
            fis.close();
        }
        catch  (Exception e) {  
        }
        txt.setText(buffer.toString());





    }





}

为什么它不起作用? 当我按下 button1 时,我转到第二个 xml.file 但 textview 为空!!!

【问题讨论】:

  • 删除 try/catch 块 - 或者可能更适用,记录异常。如果有例外,你永远不会知道。
  • 我很内向……你能详细解释一下吗?
  • try { throw new Exception("Oops"); doImportantStuff() } catch (Exception e) {} - doImportantStuff 从未被调用,但我们从未发现,因为异常被忽略了!现在,我并不是说生成了一个异常,但如果是,你永远不会知道(并且可能以一个空的StringBuffer结束)。
  • 那我该怎么办?
  • 尝试从异常中适当地恢复 - 如果你不能(或者即使你可以),log the exception。小心“盲目吞咽”异常。

标签: android


【解决方案1】:

试试这个..

    txt=(TextView)findViewById(R.id.textView1);        

    AssetManager assetManager = getAssets();
    InputStream inputStream = null;
    try {
         inputStream = assetManager.open("12.txt");
         BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
         StringBuilder total = new StringBuilder();
         String line;
         while ((line = r.readLine()) != null) {
              total.append(line);
         }
         txt.setText(total.toString());
    }
    catch (IOException e){
         e.printStackTrace();
    }

【讨论】:

  • 它可以工作......但是这些行并不合理......它是记事本问题吗???我该如何解决??
  • @user3410344 可能会将您的 TextView 宽度更改为 match_parent android:layout_width="match_parent" 并尝试。
  • 它不起作用我可以使用pdf来解决它吗?我认为是记事本问题
  • @user3410344 k 这样做。快乐编码。
  • 我也可以用你的代码来制作 pdf 吗??? pdf就像代码中的记事本???
【解决方案2】:

像这样使用代码:

          FileInputStream fstream = new FileInputStream(Environment.getExternalStorageDirectory()+filenames));
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine()) != null)   
          {
              arrayOfarray.add(strLine);
          }

【讨论】:

  • 第一行的文件名是什么???我的 txt.file 名称是 12.txt
  • 获取文件名的位置,使用路径。
  • 12.txt 在我的资产文件夹中......所以???????
  • 使用这个代码:`AssetManager am = context.getAssets(); InputStream is = am.open("test.txt");'
  • 然后 ??? txt.settext(is) ?????
【解决方案3】:

我最好的猜测是程序的运行目录不是你想象的那样,openFileInput() 会抛出一个 IOException,因为它找不到 12.txt。你的 catch-all-do-nothing 块可能隐藏了一个错误。您可能想要记录异常并中止。如果您不关心导致程序崩溃的异常情况,可以使用以下廉价技巧来获取回溯:

catch(Exception e)
{
    throw(new RuntimeException(e));
}

当我编写的代码应该是高标准项目的一部分(而不是一次性实验或其他东西),或者其他人会看到时,我会创建 MyIOException,它是 RuntimeException 的子类(可能通过中间 MyRuntimeException) 并且有一个 IOException 成员,然后当我捕获一个 IOException 时我会抛出一个包装好的 MyIOException,它的好处是让我的调用者使用基于类的异常调度。

【讨论】:

  • 我在我的代码中替换了你的捕获但是当我按下按钮时出现这个错误:不幸的是文本已经停止
【解决方案4】:
Try this code. it works for me. so it will help you.

package com.example.answerquestion;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.btn1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                File dir = new File(getFilesDir().getAbsolutePath());
                try{
                    PrintWriter out = new PrintWriter(new FileWriter(dir + "/test.txt"));
                    for (int i = 0; i < 20; i++) {
                        out.println("omg");
                    }
                    out.close();
                    File file = new File(getFilesDir().getAbsolutePath(), "/test.txt");
                    FileInputStream in = new FileInputStream(file);
                  //  FileInputStream fis=null;
                    final StringBuffer buffer= new StringBuffer();

                       // fis = openFileInput("12.txt");
                        DataInputStream dataIO = new DataInputStream(in);
                        String strLine = null;

                        if ((strLine = dataIO.readLine()) != null) {
                            buffer.append(strLine);
                        }

                        dataIO.close();
                        in.close();
                        System.out.print(buffer.toString());
                    }
                    catch  (Exception e) {  
                    }

                }

        });
    }

}

【讨论】:

    【解决方案5】:

    对不起哥们!! 我再次编辑它,现在它将完美运行!

     public class Text2 extends Activity {
            private TextView txt;
    
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    // TODO Auto-generated method stub
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.text2);
                    txt=(TextView)findViewById(R.id.textView1);  
             String mLine ="";  
            try {
                    BufferedReader reader = new BufferedReader(
                        new InputStreamReader(getAssets().open("12.txt")));
    
                    // do reading, usually loop until end of file reading  
                    mLine = reader.readLine();
    
    
                    reader.close();
                } catch (IOException e) {
                    //log the exception
                }
                txt.setText(mLine)
    
             }
    
    
    
    
    
            }
    

    【讨论】:

    • 这个代码你试过了吗???
    • mLine 无法解析为变量.......出现此错误
    • 我已经编辑了答案!!试试看
    • 我试过了,但是textview是空的.....为什么????
    猜你喜欢
    • 2017-08-22
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多