Speeding up keystroke automation

applescriptautomation

I'm on MacOS 11.2.1 . I have Automator-based AppleScript code for reading text from a file and then "typing" it into the application which is currently active. This works fine, but I need something faster. I have a 2 Meg file of text that I want to send into an app, and it takes a few hours using this Applescript code. Can anyone suggest a way to simulate typing faster than this?

on readFile(unixPath)
    set fhandle to (open for access (POSIX file unixPath))
    set txt to (read fhandle for (get eof fhandle) as «class utf8»)
    close access fhandle
    return txt
end readFile

set texttowrite to readFile("/path/to/file/containing/text")
tell application "[Target Application]" to activate
tell application "System Events"
    repeat with i from 1 to count characters of texttowrite
        keystroke (character i of texttowrite)
    end repeat
end tell

… where [Target Application] is the application into which the text will be "typed".

I need to do this instead of simply a "cp" command, because the target application is a gateway to a service on a different machine. That particular application offers no file transfer capabilities, which is why I need to do this via simulated typing.

Any suggestions about how to do this simulated typing faster?

Thank you in advance.

PS: This slowness has nothing to do with the fact that the target app manages a remote connection. If I use this code to send the data to an application on the same machine on which this AppleScript is running, the "typing" is just as slow.

Best Answer

Read the file, then extract the paragraph
Very simplified...

set theFile to open for access myPath 
set fileContents to (read theFile)
close access theFile
set myParas to count paragraphs of fileContents 
repeat with i from 1 to myParas 
    set myText to myText & "\n" & paragraph i of fileContents
end repeat
  
tell application "app" to activate
tell application "System Events" to keystroke myText