找不到文件夹JAVA macOS的真实路径

时间:2019-11-30 18:47:05

标签: html java-ee

我正在尝试在带有音频HTML标签的webapp应用程序中侦听动态文件,但是我无法将文件保存在正确的文件夹中...

这是我在eclipse中的文件结构,我想找到所选音频文件夹的路径,而无需对其进行硬编码:

enter image description here

我可以在Controller.java上运行代码,在其中添加:  1)html标记:

<audio controls><source src=\"audio/hello.wav\" type=\"audio/wav\"></audio>

2)为了创建我的文件,我正在使用

    file = new File("/Users/miguelenrile/Desktop/universidad ICAI/master-teleco-1/Primer cuatri/Arq.servicios.de.red/practicas/P10/asrTomcatEjemploCloudant/src/main/webapp/audio/hello2.wav");

显然,这是一个硬编码的目录,一旦目录系统更改,它将不起作用。

我的问题是我需要找到该路径,但是当在互联网上搜索该怎么做时,我却永远也找不到该路径,而是这些行中的某些东西:

/Users/miguelenrile/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/asrTomcatEjemploCloudant/

当粘贴到浏览器中时可以使用,但是不会在音频src希望找到的文件中创建文件,因此它将无法使用...

我试图获得前面提到的路径的东西...:

System.out.println("probada: " +getServletContext().getAttribute(ServletContext.TEMPDIR));
System.out.println(getServletContext().getContextPath());
System.out.println(getServletContext().getRealPath(dir));
System.out.println(new File(".").getCanonicalPath());
System.out.println(System.getProperty("user.dir"));
System.out.println(System.getProperty("user.home"));      
System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation());
System.out.println(getServletContext().getRealPath("/"));
System.out.println(request.getSession().getServletContext().getRealPath("/"));
System.out.println(request.getContextPath());

所有这些公式都将放在此处:

/Users/miguelenrile/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/asrTomcatEjemploCloudant/

不进入前面提到的编码路径...

我不知道我是否缺少任何东西...

总结:

我想要的路径:

/Users/miguelenrile/Desktop/universidad ICAI/master-teleco-1/Primer cuatri/Arq.servicios.de.red/practicas/P10/asrTomcatEjemploCloudant/src/main/webapp/audio/hello2.wav

我要走的路:

/Users/miguelenrile/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/asrTomcatEjemploCloudant/

谢谢

完整代码:

Controller.java     受保护的void doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException     {         PrintWriter out = response.getWriter();         out.println(“”);

    CloudantPalabraStore store = new CloudantPalabraStore();
    System.out.println(request.getServletPath());
    switch(request.getServletPath())
    {
        case "/listar":
            if(store.getDB() == null)
                  out.println("No hay DB");
            else
                out.println("Palabras en la BD Cloudant:<br />" + store.getAll());
            break;

        case "/hablar":
            //Get tghe word to translate with IBM text to Speech
            String text = request.getParameter("palabra");
            String dir = System.getProperty("user.dir");
            System.out.println("current dir = " + dir);

           /*
            System.out.println("probada: " +getServletContext().getAttribute(ServletContext.TEMPDIR));
            System.out.println(getServletContext().getContextPath());
            System.out.println(getServletContext().getRealPath(dir));
            System.out.println(new File(".").getCanonicalPath());
            System.out.println(System.getProperty("user.dir"));
            System.out.println(System.getProperty("user.home"));
            System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation());
            System.out.println(getServletContext().getRealPath("/"));
            System.out.println(request.getSession().getServletContext().getRealPath("/"));
            System.out.println(request.getContextPath());
            */


            String path = TextoAPalabras.hablar(text,getServletContext());
            System.out.println("Path que recibo en :" +path);
            out.println("<META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">");
            out.println("<audio controls><source src=\"audio/hello.wav\" type=\"audio/wav\"></audio>");
            out.println("<p>path del file: "+path +"</p> ");
            break;

        case "/insertar":
            Palabra palabra = new Palabra();
            String parametro = request.getParameter("palabra");

            if(parametro==null)
            {
                out.println("usage: /insertar?palabra=palabra_a_traducir");
            }
            else
            {
                if(store.getDB() == null) 
                {
                    out.println(String.format("Palabra: %s", palabra));
                }
                else
                {
                    parametro = Traductor.translate(parametro, "es", "en", false);
                    palabra.setName(parametro);
                    store.persist(palabra);
                    out.println(String.format("Almacenada la palabra: %s", palabra.getName()));                   
                }
            }
            break;
    }
    out.println("</html>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

}

TextoAPalabras.java:创建文件的位置

public class TextoAPalabras {

private static File FILE;

public  static String hablar(String text, ServletContext sc) {

//autenticación en el servicio de TextToSpeech;
IamAuthenticator authenticator = new IamAuthenticator("xxxxyyyyy");
TextToSpeech textToSpeech = new TextToSpeech(authenticator);

textToSpeech.setServiceUrl("https://gateway-lon.watsonplatform.net/text-to-speech/api");
//Tenemos certificado así que no es necesario disable SSL certificates
  File file = null;
try {
     file = new File("/Users/miguelenrile/Desktop/universidad ICAI/master-teleco-1/Primer cuatri/Arq.servicios.de.red/practicas/P10/asrTomcatEjemploCloudant/src/main/webapp/audio/hello2.wav");

      SynthesizeOptions synthesizeOptions =
        new SynthesizeOptions.Builder()
          .text(text)
          .accept("audio/wav")
          .voice("en-US_AllisonVoice")
          .build();




      InputStream inputStream = textToSpeech.synthesize(synthesizeOptions).execute().getResult();
      InputStream in = WaveUtils.reWriteWaveHeader(inputStream);
      copyInputStreamToFile(in,file);

      Clip clip = AudioSystem.getClip();
      System.out.println("Devuelvo el file path");
      System.out.println(file.toString());



      in.close();
      inputStream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

return file.getAbsolutePath();

}
// InputStream -> File
private static void copyInputStreamToFile(InputStream inputStream, File file) 
    throws IOException {

    try (FileOutputStream outputStream = new FileOutputStream(file)) {

        int read;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        // commons-io
        //IOUtils.copy(inputStream, outputStream);

    }
}

}

1 个答案:

答案 0 :(得分:0)

将getRealPath()与音频文件的文档根路径一起用作参数,应该将文件的实际路径交给您。

getServletContext().getRealPath("/audio/hello.wav");