【问题标题】:how to read a specific line in .java file and prints out ...?如何读取 .java 文件中的特定行并打印出...?
【发布时间】:2015-09-08 16:43:44
【问题描述】:

我正在创建一个项目,我需要在其中读取从 .java 文件中的关键字开始的特定行。

我将不得不阅读 .java 文件:

Intent myIntent = new Intent(StudentMap.this, StudentPref.class);
StudentMap.this.startActivity(myIntent);

我将如何在代码中的任何位置阅读这两行。我应该为此设置正则表达式,但是如何设置?

我正在使用:

public void onClick(View v) {

    TextView responseText = (TextView) findViewById(R.id.responseText);
    String myData = "";
String test = "Intent ";
   // String name="";
    switch (v.getId()) {
        case R.id.getExternalStorage:
            try {
                FileInputStream fis = new FileInputStream(myExternalFile);
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;

                while ((strLine = br.readLine()) != null){
                    myData = myData + strLine;



                    if (strLine.equals(test)) {

                        tv1.setText(tv1.getText() + strLine + "\n");
                    }
                    else{
                        tv1.setText(tv1.getText() + "nakaam" + "\n");

                    }

                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            responseText.setText("MySampleFile.java data retrieved from external Storage...");

            break;

    }

    tv1.setText(tv1.getText() + myData + "\n"+"\n"+"\n"+"end");

    //tv1.setText(tv1.getText() + strLine + "\n");


}

据我所知,Intent 关键字在每个文件中都是静态的,因此我可以获得像“Intent”这样的行首,但是如何仅从大文件中读取这一行和下一行..?

【问题讨论】:

    标签: java android string


    【解决方案1】:

    如果您想在关键字意图处开始您的字符串,然后读取多行,您可以执行以下操作:

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        int remainingLines = 0;
        String stringYouAreLookingFor = "";
        for(String line; (line = br.readLine()) != null; ) {
            if (line.startsWith("Intent")) {
                remainingLines = <Number of Lines you want to read after keyword>;
                stringYouAreLookingFor += line
            } else if (remainingLines > 0) {
                remainingLines--;
                stringYouAreLookingFor += line
            }    
        }
    }
    

    我想这应该让您了解如何搜索您正在寻找的字符串。

    【讨论】:

    • 你想要一个空字符串还是一个整数?
    • 它是一个整数。假设你想要包含 Intent 的行和以下 2 行,你会放 reamingLines = 2
    • 行是一个字符串。如何将字符串分配给整数。它说不兼容的类型 java.lang.string
    • 如果我把 youwant 作为字符串,它会给我两行额外的行,其中包含我不想要的文本 Intent。
    • 但还打印了剩余的两行。这是必需的,这确实使我更接近目标。赞赏。但请告诉如何删除也包含意图名称但不需要的额外行。我严格需要从 Intent 关键字开始的行。并且只有下一行,或者可能是接下来的 2、3 行,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多