【问题标题】:Get(Store) a String value in multiple String variables获取(存储)多个字符串变量中的字符串值
【发布时间】:2018-06-17 15:09:39
【问题描述】:

我正在使用 Java Files 类。这是我的代码逻辑-

if ((file.getName().contains("pictures"))) {

        //trying to get path of files

         String path = file.getAbsolutePath();
    }

我正在文件夹(和子文件夹)中搜索名为“图片”的文件并获取它的路径。此代码确实返回路径,但它们都存储在一个名为 path 的变量中。我想要做的是获取所有路径并将其存储在变量数组中。

这是我得到的输出-

D/path: /sdcard/DCIM/picture001.jpg
D/path: /sdcard/DCIM/picture0421.jpg
D/path: /sdcard/DCIM/picture4341.jpg
D/path: /sdcard/DCIM/picturs01.jpg

现在,我希望将所有这些路径存储在不同的变量中,而不是像path 这样的一个变量

   path1=/sdcard/DCIM/picture001.jpg
    path2=/sdcard/DCIM/picture0421.jpg
    path3=/sdcard/DCIM/picture4341.jpg

我尝试做的是-

ArrayList<String> myarray= new ArrayList<>();
 myarray= path;

但这会产生错误。如何实现?

【问题讨论】:

  • 你得到的字符串路径的确切值是多少
  • 与其尝试将字符串分配给数组列表,不如使用其add 方法-myarray.add(path);
  • @Sundeep 下面的代码“这是我得到的输出”
  • 我仍然无法正常工作..

标签: java android arraylist file-io


【解决方案1】:
import java.util.ArrayList;
import java.util.Scanner;

public class Arrays {


        public static void main(String[] args) 
        {
            String path = "/sdcard/DCIM/picture001.jpg /sdcard/DCIM/picture0421.jpg /sdcard/DCIM/picture4341.jpg /sdcard/DCIM/picturs01.jpg";
            Scanner scan = new Scanner(path);
            ArrayList<String> myarray= new ArrayList<>();
            while(scan.hasNext()) {
                myarray.add(scan.next());
            }

            for(int i=0; i<myarray.size(); i++) {
            System.out.println(myarray.get(i));
        }

        }

}

【讨论】:

  • "D/path:" 与此无关,因为它是 logcat 语句。所以在它上面使用分隔符是没有用的。
  • 正如你所说,它是确切的字符串,所以如果“D/path:”不存在,我使用分隔符,你可以删除该语句。
  • 而且,它还返回“s”,其中包含与“path”完全相同的路径。我希望它们存储在多个变量中,例如 path1、path2、path3 等
  • 那么您面临的实际问题是什么
  • 我希望它们存储在多个变量中,例如 path1、path2、path3 等。
【解决方案2】:
    import java.io.*;

     class JavaFile{

            public static void main(String args[]){

                String path[]=new String[1000];
                int count=0;

                File f=new File("/Users/Study/Desktop");

                if(f.exists()){

                    String list[]=f.list();

                    for(int i=0;i<list.length;i++){

                            if(list[i].contains("Sc")){
                                path[count]=new File(list[i]).getAbsolutePath();
                                count++;
                                System.out.println(list[i]);
                            }

                    }



                }
                else
                    System.out.println("Not Found");

            }


    }

【讨论】:

  • 还要检查 f.isDirectory() 是否重复同样的事情。希望对您有所帮助。
猜你喜欢
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多