springframework.core.io.Resource总是抛出java.io.FileNotFoundException

时间:2018-01-04 04:34:07

标签: java spring

我是Spring的初学者,我正在学习资源。

                       public class Tab1Fragment extends Fragment implements 
                               AdapterView.OnItemSelectedListener {

                          EditText subj,desx;
                  private ImageView mAvatarImage;
                   Button choosefile,select,submt;
                      String uid, type;
                     String MY_PREFS_NAME = "value";
                  private int PICK_PDF_REQUEST = 1;
                  TextView filetext;
//storage permission code
              private static final int STORAGE_PERMISSION_CODE = 123;
                 String uploadId;

//Uri to store the image uri
                  private Uri filePath;
               Spinner spinner,spinner2;
                       public Tab1Fragment() {
                  // Required empty public constructor
              }
            public static Tab1Fragment newInstance() {
             Tab1Fragment fragment = new Tab1Fragment();
              return fragment;
         }



@Override
public void onActivityCreated(Bundle savedInstanceState) {


    super.onActivityCreated(savedInstanceState);
}

@Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
         View rootview= inflater.inflate(R.layout.fragment_tab1, container, 
     false);
         subj=(EditText)rootview.findViewById(R.id.subj);
             choosefile=(Button)rootview.findViewById(R.id.choosefile);
                   select=(Button)rootview.findViewById(R.id.select);
            submt=(Button)rootview.findViewById(R.id.submt);
                 filetext=(TextView)rootview.findViewById(R.id.filetext);
            mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
             desx=(EditText)rootview.findViewById(R.id.desx);
          submt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            saveProfileAccount();
        }
    });
    select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showFileChooser();
        }
    });
    choosefile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadMultipart();
        }
    });
    requestStoragePermission();

    SharedPreferences prefs = 
 this.getActivity().getSharedPreferences(MY_PREFS_NAME, 
 Context.MODE_PRIVATE);
    uid = prefs.getString("uid", null);
    spinner = (Spinner)rootview.findViewById(R.id.spinner);
     spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
    // Spinner click listener
    spinner.setOnItemSelectedListener(this);
    spinner2.setOnItemSelectedListener(this);
    // Spinner Drop down elements
    List<String> deparment= new ArrayList<String>();
    deparment.add("Support");
    deparment.add("Project");

    deparment.add("Payment");
    deparment.add("Service");
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);


    List<String> priority= new ArrayList<String>();
        priority.add("low");
             priority.add("Medium");

              priority.add("High");

    ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);

    // Drop down layout style - list view with radio button
    dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner2.setAdapter(dataAdapter2);

    return rootview;
}

private void saveProfileAccount() {

    VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(NetworkResponse response) {
            String resultResponse = new String(response.data);
            try {
                JSONObject b = new JSONObject(resultResponse);
                int status = b.getInt("status");
                String data = b.getString("message");
                Log.d("Response", data);
                if (status ==100) {
                  /*  Intent intent = new Intent(getActivity(),Skills.class);
                    startActivity(intent);*/

                    Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
                }

                } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            NetworkResponse networkResponse = error.networkResponse;
            String errorMessage = "Unknown error";
            if (networkResponse == null) {
                if (error.getClass().equals(TimeoutError.class)) {
                    errorMessage = "Request timeout";
                } else if (error.getClass().equals(NoConnectionError.class)) {
                    errorMessage = "Failed to connect server";
                }
            } else {
                String result = new String(networkResponse.data);
                try {
                    JSONObject response = new JSONObject(result);
                    String status = response.getString("status");
                    String message = response.getString("message");

                    Log.e("Error Status", status);
                    Log.e("Error Message", message);

                    if (networkResponse.statusCode == 404) {
                        errorMessage = "Resource not found";
                    } else if (networkResponse.statusCode == 401) {
                        errorMessage = message+" Please login again";
                    } else if (networkResponse.statusCode == 400) {
                        errorMessage = message+ " Check your inputs";
                    } else if (networkResponse.statusCode == 500) {
                        errorMessage = message+" Something is getting wrong";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Log.i("Error", errorMessage);
            error.printStackTrace();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("userid", uid);
            params.put("department", spinner.getSelectedItem().toString());
            params.put("priority", 
           spinner2.getSelectedItem().toString().trim());

            params.put("subject", subj.getText().toString().trim());
            params.put("description",desx.getText().toString().trim());
            return params;
        }

        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            // file name could found file base or direct access from real path
            // for now just get bitmap data from ImageView
            params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));


            return params;
        }
    };

    VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);

}

我编写上面的简单代码只是为了使用类路径来加载.xml文件。

以下是我的项目的层次结构: enter image description here

然后我尝试了package com.smart.beanfactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class BeanLifeCycle { private static void LifeCycleInBeanFactory() { Resource res = new ClassPathResource("classpath:com/smart/beanfactory/beans.xml"); try { System.out.println(res.getURL()); } catch (Exception e) { System.out.println(e.fillInStackTrace()); } } public static void main(String[] args) { LifeCycleInBeanFactory(); } } 中的绝对文件路径 但那也行不通。 它只是告诉我“java.io.FileNotFoundException:类路径资源[Users / haoxu / Documents / Code / Java / anotherchapter4 / src / main / resources / com.smart / beanfactory / beans.xml]无法解析为URL,因为它不存在 “

----------- --------更新

我将代码修改为:

Resource res = new ClassPathResource("file:/Users/haoxu/Documents/Code/Java/anotherchapter4/src/main/resources/com.smart/beanfactory/beans.xml");

但我仍然得到“java.io.FileNotFoundException:类路径资源[com / smart / beanfactory / beans.xml]无法解析为URL,因为它不存在”

3 个答案:

答案 0 :(得分:2)

classpath:

不需要前缀ClassPathResource

答案 1 :(得分:0)

使用您的代码尝试以下行

Resource res = new ClassPathResource("/resources/com/smart/beanfactory/beans.xml");

答案 2 :(得分:0)

我复制并粘贴文件&#34; beans.xml&#34;到目录&#34; target / classes / com / smart / beanfactory /&#34;。层次结构如下所示 enter image description here

我的代码如下:

package com.smart.beanfactory;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;

public class BeanLifeCycle {
    private static void LifeCycleInBeanFactory() {
        Resource res = new ClassPathResource("com/smart/beanfactory/beans.xml");
        try {
            System.out.println(res.getURL());
        } catch (Exception e) {
            System.out.println(e.fillInStackTrace());
        }
    }

    public static void main(String[] args) {
        LifeCycleInBeanFactory();
    }
}

结果是&#34;文件:/Users/haoxu/Documents/Code/Java/anotherchapter4/target/classes/com/smart/beanfactory/beans.xml &#34;

这实际上是文件的路径。但它位于目标目录中。我认为那真是奇怪