如何用ExecuteScript将TXT文件内容加载到NiFi属性并添加Bearer前缀
Solution to Load TXT Content into NiFi Attribute with "Bearer " Prefix
I get it—your current ExecuteScript code is stuck using getAttribute() which only pulls existing attributes, not the actual content of the TXT file. To access the file's content and add that "Bearer " prefix, you need to use NiFi's session API to read the flow file's input stream directly.
Here's a working Groovy script for ExecuteScript that does exactly what you need:
import org.apache.nifi.processor.io.StreamCallback import java.nio.charset.StandardCharsets def flowFile = session.get() if (!flowFile) return try { // Variable to hold the file content def tokenContent = "" // Read the flow file content using a StreamCallback flowFile = session.read(flowFile, new StreamCallback() { @Override void process(InputStream inStream, OutputStream outStream) throws IOException { // Read all bytes from the input stream and convert to UTF-8 string tokenContent = new String(inStream.readAllBytes(), StandardCharsets.UTF_8).trim() // Write the original content back (we're not modifying the file itself) outStream.write(tokenContent.getBytes(StandardCharsets.UTF_8)) } }) // Prepend "Bearer " and set as an attribute (change "Authorization" to your desired attribute name) def bearerToken = "Bearer " + tokenContent flowFile = flowFile.putAttribute("Authorization", bearerToken) // Send the processed flow file to success relationship session.transfer(flowFile, REL_SUCCESS) } catch (Exception e) { log.error("Error processing flow file: ${e.message}", e) session.transfer(flowFile, REL_FAILURE) }
Key Details:
- Reading Content: The
StreamCallbackhandles safely reading the flow file's input stream and writing the original content back (since we don't want to alter the file itself, just add an attribute). - Encoding: We're using UTF-8, which is standard for most text files. If your TXT uses a different charset (like ISO-8859-1), replace
StandardCharsets.UTF_8with the appropriate charset. - Trimming: The
.trim()removes leading/trailing whitespace from the token content—if you need to preserve all whitespace (like newlines or spaces), just remove this part. - Attribute Name: I used "Authorization" as the attribute name since that's common for bearer tokens, but you can change it to whatever fits your workflow.
Why Your Original Code Didn't Work:
getAttribute() only retrieves values that were already set as flow file attributes (e.g., from a previous processor or NiFi's default attributes). To access the actual content of the flow file (the TXT data), you must use session.read() to interact with the input stream directly.
内容的提问来源于stack exchange,提问作者J.Zil
相关产品推荐
相关产品推荐

