【问题标题】:Return String And Use It In Every Differnt String [closed]返回字符串并在每个不同的字符串中使用它[关闭]
【发布时间】:2015-04-27 06:18:03
【问题描述】:
public void a(){

        File dir = new File("/mnt/sdcard/files");
        String[] children = dir.list();

        for (String s : children){

            if(s.contains("cache")){

            System.out.println(s);

            // Means Found
            Toast.makeText(getApplicationContext(), "Found", Toast.LENGTH_SHORT).show();

            }
        }

        // Means No Found
        Toast.makeText(getApplicationContext(), "Not Found", Toast.LENGTH_SHORT).show();
        return;
    }

我真正想要的就是这样的

  • 我在“/mnt/sdcard/files”中有很多文件

  • 我想搜索包含一些已知名称的文件,让我们使用“缓存” 我可以这样列出

System.out.println(s);

输出将是

  • cache.bin
  • newcachete.txt
  • 文件缓存

类似的东西

但我真正想要的是这个函数返回包含单词“缓存”的文件的全名,并在另一个函数的不同字符串中为其赋值

例如,如果这个函数返回 String = newcachete.txt,这样我就可以在另一个函数中分配它的值

public void newfunction(){

String new = a();
// this string will contain newcachete.txt

}

但由于可能有很多文件包含此名称,所以我想返回我可以在新函数中分配的所有文件名

例如

public void newfunction(){

String new = a();
// this string will contain newcachete.txt
// and like that i want it to conatain every different name
/*
String a = cachenew.bin;
String b = filecachete.txt;
*/

}

在不同的功能 有什么办法吗?

感谢您的回答,感谢您给我时间:)

我正在寻找更好的答案

【问题讨论】:

  • 你可以将它存储在数组中。
  • 你能写一些代码帮助吗?
  • 什么是cachenew.bin?
  • 这是我随机取的文件名:)
  • 我已按要求进行了编辑,现在它会清理并让您更好地理解 :)

标签: java android


【解决方案1】:

试试

public List a(){

    File dir = new File("/mnt/sdcard/files");
    String[] children = dir.list();
    ArrayList <String> files = new ArrayList <String> ();

    for (String s : children){

        if(s.contains("cache")){

          System.out.println(s);
          files.add (s);

        }
    }

    return files;
}

【讨论】:

  • 但我怎么能在下一个函数中使用它,比如 String a = a()[0] index 0 和 [1];类似的东西
  • 我不明白你在问什么
  • 我的意思是列表将所有名称加在一起,我正在寻找的是在不同的字符串中放置不同的值,例如字符串 a = 包含第一个缓存文件,字符串 b = 包含第二个缓存文件,但列出结果在 [cache1,cache2] 但我希望它们中的每一个都在不同的字符串中
【解决方案2】:

如果名称 newold 具有某些含义,您可以返回 Map&lt;String,String&gt;,其中键是名称(例如,newold),值是文件名。

例如,在您的示例中

字符串 a = cachenew.bin;字符串 b = cacheold.bin;

这样我可以使用

字符串 new = a;字符串旧 = b;

你可以写(假设cachenew.bincacheold.bin是变量,就像你写的那样):

public Map<String,String> a() {
  ...


    Map<String, String> result = new HashMap<String,String>();

    result.put("new", cachenew.bin);
    result.put("old", cacheold.bin);

    return result;
}

然后把它当作

Map<String, String> res = a();

String newS = res.get("new");   // "new" is not a good variable name :-)
String oldS = res.get("old");

【讨论】:

  • 我会投上一票,因为它也可以,但不知何故我自己修复了它以使其变得简单,感谢您的时间和精力兄弟:))))
猜你喜欢
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 2021-03-18
  • 2017-11-02
  • 1970-01-01
  • 2021-07-19
相关资源
最近更新 更多