有没有一种简单的方法来配置流程(flow),从类路径(classpath)读取单个文件一次?我不需要轮询(poll)文件。我只需要读取已知文件并将其内容设置为消息载荷(message payload)。
有没有一种简单的方法来配置流程(flow),从类路径(classpath)读取单个文件一次?我不需要轮询(poll)文件。我只需要读取已知文件并将其内容设置为消息载荷(message payload)。
使用set-payload
消息处理器和MEL表达式:
<set-payload value="#[Thread.currentThread().getContextClassLoader().getResourceAsStream('my-file.abc')]" />
由于某些原因,我不能让David Dossot提出的解决方案工作。我受到了这个答案的启发,想出了另一个解决方案。
<spring:bean id="myResource" class="org.apache.commons.io.IOUtils" factory-method="toString">
<spring:constructor-arg value="classpath:path/to/myResource.txt" type="java.io.InputStream"/>
</spring:bean>
然后您可以按以下方式使用set-payload
<set-payload value="#[app.registry.myResource]" doc:name="Set Payload"/>
这将导致将文件内容作为字符串设置到有效载荷中。
此方法的优点在于,资源文件的内容仅加载一次到 String 类型的 bean 中。因此,如果您的 set-payload 语句经常执行,这可能会提高性能。
<parse-template location="my-resurce.txt" doc:name="Load resource as a String"/>
我正在尝试抛出Java类转换器,以便您可以使用以下内容
注意:路径是包含要读取的文件的直接包,将路径存储在Mule变量中,然后读取文件内容并将其值存储到有效载荷中
.
public class PayloadFileReader extends AbstractMessageTransformer {
public Object transformMessage(MuleMessage message, String outputEncoding)
throws TransformerException {
String result = "";
try {
result = readFileTest(message.getInvocationProperty("path")
.toString());
} catch (Exception e) {
e.printStackTrace();
}
message.setPayload(result);
return message;
}
public String readFileTest(String path) throws FileNotFoundException,
IOException, Exception {
ClassLoader classLoader = getClass().getClassLoader();
"+classLoader.getResource("samples/v3/addVal-request.sample").getFile());
File file = new File(classLoader.getResource(path).getFile());
FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = null;
StringBuilder stringBuffer = new StringBuilder();
String line;
try {
bufferReader = new BufferedReader(fileReader);
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferReader != null) {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuffer.toString();
}
<spring:beans>
<spring:import resource="classpath:sample-mule-integration.xml"/>
</spring:beans>
或者您可以尝试将文件放置在属性占位符中,如下所示
<context:property-placeholder location="file:E:\NewMuleWorkSpace\springbeanproperties\src\main\resources\property.properties"/>
或者您甚至可以使用带有示例代码的Groovy组件读取文件:
File file = new File("C://Users//schiraboina//Desktop//123.txt")
payload=file.getText()
<parse-template location="my-resurce.txt" doc:name="Load resource as a String"/>
文件可以完全不包含任何MEL表达式,这种情况下它实际上会按原样加载,并成为有效载荷。
<scripting:component doc:name="Get xls File">
<scripting:script engine="Groovy"><![CDATA[new File('C:/project/src/main/resources/account.xls').getText('UTF-8')]]></scripting:script>
</scripting:component>