我正在使用本指南制作自己的web服务,该指南基于邮政编码(从客户端收到),返回一个包含温度、城市、谷歌地图链接和.wav
天气报告的对象作为byte[]
。我的web服务实际上使用另一个web服务来获取添加的数据,就像在这里一样。但我的网络服务实际做的是,它根据数据生成谷歌地图URL和声音文件。
web服务成功地将城市和温度添加到返回的对象中(客户端获取数据),但当我的web服务试图为声音文件创建字节数组时,我遇到了问题。
首先,我还创建了一个新类,它在同一个项目中,与web服务类具有相同的代码,只是它还有一个主函数,所以我可以离线运行它,看看代码是否有效。我用它来测试在web服务上不起作用的代码。确切地说,这段代码本身运行得非常好:
public class Sound {
public static byte[] getSound (String text) throws IOException {
Voice voice;
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin");
FreeTTS freeTTS = new FreeTTS(voice);
freeTTS.setAudioFile("recording.wav");
freeTTS.startup();
voice.allocate();
voice.speak(text);
voice.deallocate();
freeTTS.shutdown();
File f = new File("recording.wav");
if (f.exists() && !f.isDirectory()) {
System.out.println("it exists");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream("recording.wav"));
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
out.flush();
byte[] audioBytes = out.toByteArray();
return audioBytes;
}
public static void main (String[] args) throws IOException {
byte[] data = Sound.getSound("Some text");
System.out.println(data);
}
}
但是当web服务运行此代码时,会出现异常。首先,意味着recording.wav已经存在(用上面的测试类生成),我没有生成新的.wav,也就是说,我正在尝试从recording.waw中生成一个字节[]。在测试类中,它说"recording.wav"存在,而当运行的web服务检查文件是否存在时,我会得到一个空指针异常,即使webservice和测试类在同一个项目/文件夹中。
java.io.FileNotFoundException:recording.wav(系统找不到指定的文件)在java.io.FileInputStream.open0(本机方法)
其次,如果我试图在运行的web服务上生成声音文件,则会抛出一个异常:VoiceManager.getInstance();
客户端堆栈跟踪(仅复制第一行):
org.apache.axis2.AxisFault: com/sun/speech/freetts/VoiceManager
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:531)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:375)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
Web服务方面:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:212)
我已经尝试重新部署web服务和客户端,但没有任何变化。现在,为什么这些错误是在作为web服务运行时发生的,而它们在脱机运行时运行得非常好?
要修复FileNotFoundException,您应该检查当前工作目录是什么,因为它很可能在源目录和测试目录之间有所不同。
或者,您可以使用Java的ClassLoader来加载该文件。ClassLoader的工作方式是从项目目录中进行搜索,而不考虑当前的工作目录。所以
URL url = Sound.class.getClassLoader().getResource("/path/to/recording.wav");
File f = new File(url.toURI());
很确定我找到了答案。web服务使用的路径与项目中的普通类不同。关于java.lang.reflect.InvocationTargetException
,web服务也不使用与其他计算机相同的lib
文件夹,我不得不将所有.jar
文件复制到WebContent/WEB-INF/lib
文件夹中。