Automator - Loop through a text file and process data through a 3rd party software
Just stumbled on Automator the other day (I am a mac n00b) and would like to automate the processing of a text file, line-by-line, using a third party tool. I would like Automator to loop through the text file one line at a time, copy the string and keep as a variable. Next, place the variable data (copied string) into the text field of the 3rd party software for processing. Once the processing is complete, I would like Automator to fetch the next line/string for processing. I see items like "copy from clipboard" and "variables" within the menu but I am not finding much documentation on how to utilizle this tool. Just hear how potentially powerful it is.
The 3rd party software is not a brand name, just something made for me to process text. I may have to use mouse clicks or tabs + [return] to navigate with Automator. A term I heard on Bn Walldie's itunes video series was "scriptable software" for which I don't think this 3rd party app would be.
Kind regards,
jw
Good news and bad news...
The good news is that it should be entirely possible to automate your workflow.
The bad news is that it will be a nightmare to implement via Automator, if it's even possible.
Automator is, essentially a pretty interface on top of AppleScript/Apple Events, and with the pretty interface comes a certain stranglehold on features. Knowing how to boil rice might make you a cook, but understanding flavor profiles and ingredient combinations can make you a chef, and it's the same with AppleScript and Automator. Automator's good at getting you from points A to B but if there are any bumps in the road (e.g. the application you're using isn't scriptable) then it falls apart.
What I'm getting at is that your requirements are pretty simple to implement in AppleScript because you can get 'under the hood' and do exactly what you want, as opposed to Automator's restricted interface.
The tricky part is that if no one else can see this app it's going to be hard to tell you what to do.
I can give you the basics on reading a file and iterating through the lines of text in it, and I can show you how to 'type' text in any given application, but it may be up to you to put the pieces together.
Here's one way of reading a file and working through each line of text:
-- ask the user for a file:
set theFile to (choose file)
-- read the file contents:
set theFileContents to (read file theFile)
-- break out the lines/paragraphs of text:
set theLines to paragraphs of theFileContents
-- now iterate through those lines, one by one:
repeat with eachLine in theLines
-- code to perform for eachLine goes here
end repeat
Once you have a line of text (eachLine in the above example) you can 'type' that into another application via something like:
tell application "AppName" to activate
tell application "System Events"
tell process "AppName"
keystroke eachLine
end tell
end tell
Here the AppleScript is activating the application and using System Events to emulate typing the contents of the eachLine variable into the process. Put this inside your repeat loop and you're almost there.
Similar Messages
-
How can FMS create a text file and write data into it in the Server application folders?
Recently, I writed a programe about creating a text file and writing data into it in the server application folder. My code is as following:
var fileObj = new File("/MyApp/test.txt");
if( fileObj != null)
if(fileObj.open( "text", "append"))
fileObj.write( " ———— Chat Info Backup ————\r\n" );
fileObj.close( );
trace("Chat info backup document :" + fileObj.name + " has been created successfully!");
But when I run it, FMS throw the error as following: File operation open failed ; TypeError: fileObj has no properties.
Can you help me ? Thanks in advance.
Supplement: The text file named test.txt doesn't exist before create the fileObj, an instance of File Class.Is MyApp the name of the application directory, or is it a child of the application directory? If myApp is the app name, just use test.txt as the path flag in the file constructor.
-
How do I transfer photo files from desktop to ipad without 3rd party software?
how do I transfer photo and music files from my laptop to ipad2 without purchasing a 3rd party software?
You can use iTunes which is free (http://www.apple.com/itunes) - and that is the only way to sync music from a computer to the iPad
Syncing photos via iTunes : http://support.apple.com/kb/HT4236 . You need to sync all photos that you want on the iPad together in one go, as only the most recent remains on the iPad - not including photos in a subsequent sync is how you delete them from the iPad -
Advice on uploading files and process data
Hi, I'm building an Apex application. It requires that users can sometimes upload data (csv) that will be validated and inserted into the database.
For now I've created a component that uploads the file and copy it to my UPLOADED_FILES archive table as a blob. Now I need to create a process that review data from blob and, if posible, inform the user of incorrect lines.
It seems that I need to recreate the file on the oracle server from the blob, then use SQL Loader to create an external table from that file and finally run my own validate/copy procedure over the external table data.
So my questions are:
- Is there a more proper way of doing this?
- Can I create the external table directly from the blob, without recreating the file, and an oracle directory?
- When using sql loader, how can I deal with quotes in the text? (the csv is generated from an spreedsheet, it can have text data with quotes that will be scaped, so a posible line will be (three fileds separated by semicolons):
my data 1;"my data 2""some escaped quotes here""and a semicolon inside ; my data 2 final";my data 3;
Will work the declaration: fields terminated by ";" optionally enclosed by '"' ?
note '"' = apostrophe+quotation+apostrophe
Thanks for your advice.user3917161 wrote:
It seems that I need to recreate the file on the oracle server from the blob, then use SQL Loader to create an external table from that file and finally run my own validate/copy procedure over the external table data.
So my questions are:
- Is there a more proper way of doing this?The only other option is to manually parse the LOB yourself. So until Oracle provides external tables on LOBS too, this approach of writing it to external file for loading as an external table is a necessary evil.
- Can I create the external table directly from the blob, without recreating the file, and an oracle directory?No.
From Oracle® Database Administrator's Guide:
"<i>Oracle Database provides two access drivers for external tables. The default access driver is ORACLE_LOADER, which allows the reading of data from external files using the Oracle loader technology. The ORACLE_LOADER access driver provides data mapping capabilities which are a subset of the control file syntax of SQL*Loader utility. The second access driver, ORACLE_DATAPUMP, lets you unload data—that is, read data from the database and insert it into an external table, represented by one or more external files—and then reload it into an Oracle Database.</i>"
Perhaps we'll get a 3rd access driver in future that either supports LOBs, or enables us to define our own access driver (all that is needed as output from the driver is text lines - and this should not be that difficult to standardise as a custom interface to implement).
- When using sql loader, how can I deal with quotes in the text? (the csv is generated from an spreedsheet, it can have text data with quotes that will be scaped, so a posible line will be (three fileds separated by semicolons):
my data 1;"my data 2""some escaped quotes here""and a semicolon inside ; my data 2 final";my data 3;
Will work the declaration: fields terminated by ";" optionally enclosed by '"' ?
note '"' = apostrophe+quotation+apostropheBest is to try it and see whether it works. Also refer to the Oracle® Database Utilities for SQL*Loader syntax and options. -
Using servlets to read from text file and insert data
Hi,
Can I use a servlet to read from a space delimited text file on the client computer and use that data to insert into a table in my database? I want to make it easy for my users to upload their data without having to have them use SQL*Loader. If so can someone give me a hint as how to get started? I appreciate it.
Thanks,
ColbyCreate a page for the user to upload the file to your webserver and send a message (containing the file location) to a server app that will open the file, parse it, and insert it into your database. Make sure you secure the page.
or
Have the user paste the file into a simple web form that submits to a servlet that parses the data and inserts it into your db. -
Fstream on a text file and exel data connection breaking
Hello,
I am writing to a text file using C++ code below (VS 2008). Then I do a "Data Connection" from excel2013 to this text file: the purpose of this is to have a "live" display of some graphs based on this log file. Parameters
of the data connection is shown below.
That works fine for some time (a few hours), then for some reason, the log file stops being updated, although the C++ program is still running. No error message displayed.
Same thing happens if my C++ program just ouputs on the console using cout<< and I redirect the ouput in a logfile using the redirect DOS ">".
Anyone has any idea??
It is is so magical to have this live excel view of my batches, I would love to use that! Thanks.
LogFile.open(LogFileName.c_str(), ios::app);
if (!LogFile.is_open())
cerr << "Could not open: " << LogFileName << endl;
else LogFile << "This data" << endl;LogFile.Close();Does the problem occur when some large file size is reached, such as 2G? The issue can be caused by some limitation of older library (https://connect.microsoft.com/VisualStudio/feedback/details/627639)
or by a limitation of Excel.
If the issue is observed even on medium files, then try analyzing the status of stream (LogFile.bad() etc.) after “<<”. Perhaps it fails occasionally when Excel accesses the file. Check you program when Excel is stopped. -
Parse text file and retrieve data
Hi,
I have a log file with comma separated entries in each line. Each line has about 50 or more integer values logged for statistical analysis. What i need to do is to be able to parse this text file Line by line and retrieve data say nth entry in each row of file. Basically, like i need a certain column from a table. Column selection may vary. I can have user need 10th entry or 25th entry or more than one entries.
Please help me with suggestions for how to do this efficiently . Keep in mind log file can be huge at certian times.
Thanks
-Anupmahere's something to get you started
public void parseFile(File file) throws IOException{
String lin = null; // string to hold each line in the text file
BufferedReader in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null){
processLine(line);
public void processLine(String line){
String tokens = line.split(","); // tokenize the line - deliminator is a comma
for (int i = 0; i < tokens.length; i++){
try{
int num = Integer.parseInt(tokens);
System.out.println(" The integer is = " + num);
catch(NumberFormattedException ee){} -
Reading a text file and using data to plot a graph
Dear Friends,
I have the following problem...
I have a text data looking like this;
100000000
1003ff001
1010013ff
1000003ff
1023fe001
102000000
1023ff3ff
1010013fd
0ff0033fc
0ff002001
0fe3fd3ff
0ff000002
100000000
1003ff001
1010013ff
1000003ff
1023fe001
102000000
1023ff3ff
1010013fd
0ff0033fc
0ff002001
0fe3fd3ff
0ff000002
My Code should have a button , when you click that button it should ask you to choose a txt file to open this file from a specific place. The Indicators of the front panel should show me the ID , Name and Date. The data;
100000000
1003ff001
1010013ff
1000003ff
1023fe001
102000000
1023ff3ff
1010013fd
the first 3 bits belong to X axis, the next 3 bits belong to Y and the rest 3 belongs to Z axis. I have to convert those values to Decimal system, and plot them in a graph, 10 times a second , which means after converting and plotting 10 values , one second is over.
I would aprriciate it very much if you could help me in this case....
Thanks in advance.
Message Edited by Support on 11-13-2007 01:03 PM
Message Edited by Support on 11-13-2007 01:04 PMSome questions a teacher might ask:
What's the display setting for the "\n" string diagram constant? Why?
Is it better to read the file one line at a time or all at once?
What would you do to be able to stop the chart display before it runs out of data?
What would be different if we combine the two FOR loops into one?
How would you display the header as a multiline string instead of an array of strings?
Why is the scan format %03x instead of %3x? Would it make a difference?
What is the purpose of the two items of the property node?
What would you need to change to plot the data every 50ms? (change in two places!)
Why is the error output of the property node wired to the first FOR loop? (After all, the error value is not really used anywhere there!)
Instead of the two "array subset" operations, we could do it with one icon. Which one? (two possibilities!)
So... be prepared!
Message Edited by altenbach on 10-29-2007 11:31 AM
LabVIEW Champion . Do more with less code and in less time . -
Reading through a text file and then sorting
I'm having a lot of problems with this.
I have to read through a text file and I have to split the string up so that it is seperated into individual tokens. A line from the text file looks like this. addEvent(new Bell(tm + 9000)). I have to grab the addEvent, new, Bell, tm and 9000 and store it in a linkedlist. After reading through the whole text file I have to sort the the linked list based on the number. ie: 9000. Is there any way to do this? I currently break up the text file using a StringTokenizer object but then i am uncertain on how to add it to a linked list and then sort each line based on the number. Any help would be appreciated.
JoeSorry to bother you Ben but I just can't get my head wrapped around this. Here is exactly what I have to do:
After reading, Events must be stored in the EventSet according to the time they are to occur. Assume that no time number is more than 8 digits long. Restart() must be able to deal appropriately with any order of the Events. To accomplish this have Restart() save the relevant Event information in an LinkedList of strings and sort the Events by time before adding each event to EventSet. Use the <list>.add() to set up your linked list. This is shown in c09:List1.java and Collections.sort(<list>) shown in c09:ListSortSearch. Modify the Bell() to output a single "Bing!". When you read in a Bell event generate the appropriate number of Bell events as indicated by rings. These must be set to the correct times. This is an alternative to generating the new Bell events within Bell(). It will allow them be sorted into their correct time sequence. At this point the output of the program should be identical the original program.
After the intitial start, when restarting Restart() must provide to the user the option to recreate the EventSet from the linked list or read in a new file (supplied by the user). This must be achieved by prompting the user at the console. Please also allow the user the option to quit the program at this stage.
Main Program Code:
public class GreenhouseControls extends Controller
private boolean light = false;
private boolean water = false;
private String thermostat = "Day";
private boolean fans = false;
private class FansOn extends Event
public FansOn(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn on the Fans.
fans = true;
public String description()
return "Fan is On";
private class FansOff extends Event
public FansOff(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn off the Fans.
fans = false;
public String description()
return "Fans are Off";
private class LightOn extends Event
public LightOn(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn on the light.
light = true;
public String description()
return "Light is on";
private class LightOff extends Event
public LightOff(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn off the light.
light = false;
public String description()
return "Light is off";
private class WaterOn extends Event
public WaterOn(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
water = true;
public String description()
return "Greenhouse water is on";
private class WaterOff extends Event
public WaterOff(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
water = false;
public String description()
return "Greenhouse water is off";
private class ThermostatNight extends Event
public ThermostatNight(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
thermostat = "Night";
public String description()
return "Thermostat on night setting";
private class ThermostatDay extends Event
public ThermostatDay(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
thermostat = "Day";
public String description()
return "Thermostat on day setting";
// An example of an action() that inserts a
// new one of itself into the event list:
private int rings;
private class Bell extends Event
public Bell(long eventTime)
super(eventTime);
public void action()
// Ring every 2 seconds, 'rings' times:
System.out.println("Bing!");
if(--rings > 0)
addEvent(new Bell(System.currentTimeMillis() + 2000));
public String description()
return "Ring bell";
private class Restart extends Event
public Restart(long eventTime)
super(eventTime);
public void action()
long tm = System.currentTimeMillis();
// Instead of hard-wiring, you could parse
// configuration information from a text
// file here:
try
BufferedReader in = new BufferedReader(new FileReader("Event Config.txt"));
String str;
String[] l1 = new String[5];
LinkedList l2 = new LinkedList();
while((str = in.readLine()) != null )
StringTokenizer st = new StringTokenizer(str, "(+); ");
int nIndex = 0;
while (st.hasMoreTokens())
l1[nIndex] = st.nextToken();
//System.out.println(st.nextToken());
nIndex++;
l2.add(l1);
String[] s1 = (String[])l2.get(1);
for(int i = 0; i < s1.length; i++)
System.out.println(s1);
Comparator comp = s1[4];
Collections.sort(l2, comp);
in.close();
catch (IOException e)
rings = 5;
addEvent(new ThermostatNight(tm));
addEvent(new LightOn(tm + 1000));
addEvent(new LightOff(tm + 2000));
addEvent(new WaterOn(tm + 3000));
addEvent(new WaterOff(tm + 8000));
addEvent(new Bell(tm + 9000));
addEvent(new ThermostatDay(tm + 10000));
// Can even add a Restart object!
addEvent(new Restart(tm + 20000));*/
public String description() {
return "Restarting system";
public static void main(String[] args) {
GreenhouseControls gc =
new GreenhouseControls();
long tm = System.currentTimeMillis();
gc.addEvent(gc.new Restart(tm));
gc.run();
} ///:~
Examples File:
addEvent(new ThermostatNight(tm));
addEvent(new Bell(tm + 9000));
addEvent(new Restart(tm + 20000));
addEvent(new LightOn(tm + 1000));
addEvent(new WaterOn(tm + 3000));
rings = 5;
addEvent(new FansOn(tm + 4000));
addEvent(new LightOff(tm + 2000));
addEvent(new FansOff(tm + 6000));
addEvent(new WaterOff(tm + 8000));
addEvent(new WindowMalfunction(tm + 15000));
addEvent(new ThermostatDay(tm + 10000));
EventSet.java Code:
// This is just a way to hold Event objects.
class EventSet {
private Event[] events = new Event[100];
private int index = 0;
private int next = 0;
public void add(Event e) {
if(index >= events.length)
return; // (In real life, throw exception)
events[index++] = e;
public Event getNext() {
boolean looped = false;
int start = next;
do {
next = (next + 1) % events.length;
// See if it has looped to the beginning:
if(start == next) looped = true;
// If it loops past start, the list
// is empty:
if((next == (start + 1) % events.length)
&& looped)
return null;
} while(events[next] == null);
return events[next];
public void removeCurrent() {
events[next] = null;
public class Controller {
private EventSet es = new EventSet();
public void addEvent(Event c) { es.add(c); }
public void run() {
Event e;
while((e = es.getNext()) != null) {
if(e.ready()) {
e.action();
System.out.println(e.description());
es.removeCurrent();
} ///:~
Event.java Code
abstract public class Event {
private long evtTime;
public Event(long eventTime) {
evtTime = eventTime;
public boolean ready() {
return System.currentTimeMillis() >= evtTime;
abstract public void action();
abstract public String description();
} ///:~
Is this problem easier than I think it is? I just don't know what to add to the linkedList. A LinkedList within a linkedList? I find this problem pretty difficult. Any help is muchly appreciated.
Joe -
Having trouble reading specific lines from a text file and displaying them in a listbox
I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dll"
Below is the code from that form.
Option Strict On
Option Infer Off
Option Explicit On
Public Class frmInventoryReport
Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
Dim intTemp As Integer
intTemp = lineNumber
Return lines(lineNumber - 1)
lineNumber = intTemp
End Function
Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
End Class
Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it. Is there anything other than name and cage number that should be associated with each animal?
You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple. Here's a simple class example:
Public Class Animal
Public Property Name As String
Public Property Cage As String
Public Overrides Function ToString() As String
Return String.Format("{0} - {1}", Name, Cage)
End Function
End Class
With that you can use a routine like the following to loop through all of the files and read each one:
Dim animals As New List(Of Animal)
Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
Using reader As New System.IO.StreamReader(filePath)
Dim lineIndex As Integer = 0
Dim currentAnimal As New Animal
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
If lineIndex = 0 Then
currentAnimal.Name = line
ElseIf lineIndex = 22 Then
currentAnimal.Cage = line
Exit While
End If
lineIndex += 1
End While
animals.Add(currentAnimal)
End Using
Next
'do something to display the animals list
Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView. If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
There are lots of options depending on what you want and what all you need to do.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all" -
Urgent Help:read from text file and write to table
Hi,
I'm a super beginner looking for a vi to read this data from a text file and insert it into a table:
#19
Date: 05-01-2015
ID= 12345678
Sample_Rate= 01:00:00
Total_Records= 2
Unit: F
1 03-23-2015 10:45:46 70.1 3.6
2 03-23-2015 11:45:46 67.7 2.7
Output table
# date time x y Sample rate Total Records
1 03-23-2015 10:45:46 76.8 2.8 01:00:00 2
2 03-23-2015 10:45:46 48.7 2.1 01:00:00 2
Thanks for your help in advance.
Attachments:
sample.txt 1 KBjcarmody wrote:
Will there always be the same number of rows of noise header information?
Show us how you've read the data and what you've tried to do to parse it. Once you've got the last rows, you can loop over them using Spreadsheet String to Array (after cleaning up a few messy spaces).
Jim,
I didn't know you're that active on here.
Yes, There will always be the same number of noise header information.
I'll show you in person
Regards, -
Where does this java program read a text file and how does it output the re
someone sent this to me. its a generic translator where it reads a hashmap text file which has the replacement vocabulary etc... and then reads another text file that has what you want translated and then outputs translation. what i don't understand is where i need to plugin the name of the text files and what is the very first line of code?
[code
package forums;
//references:
//http://forums.techguy.org/development/570048-need-write-java-program-convert.html
//http://www.wellho.net/resources/ex.php4?item=j714/Hmap.java
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
public class Translate {
public static void main(String [] args) throws IOException {
if (args.length != 2) {
System.err.println("usage: Translate wordmapfile textfile");
System.exit(1);
try {
HashMap words = ReadHashMapFromFile(args[0]);
System.out.println(ProcessFile(words, args[1]));
} catch (Exception e) {
e.printStackTrace();
// static helper methods
* Reads a file into a HashMap. The file should contain lines of the format
* "key\tvalue\n"
* @returns a hashmap of the given file
@SuppressWarnings("unchecked")
private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException {
BufferedReader in = null;
HashMap map = null;
try {
in = new BufferedReader(new FileReader(filename));
String line;
map = new HashMap();
while ((line = in.readLine()) != null) {
String[] fields = line.split("\\t", 2);
if (fields.length != 2) continue; //just ignore "invalid" lines
map.put(fields[0], fields[1]);
} finally {
if(in!=null) in.close(); //may throw IOException
return(map); //returning a reference to local variable is safe in java (unlike C/C++)
* Process the given file
* @returns String contains the whole file.
private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException {
BufferedReader in = null;
StringBuffer out = null;
try {
in = new BufferedReader(new FileReader(filename));
out = new StringBuffer();
String line = null;
while( (line=in.readLine()) != null ) {
out.append(SearchAndReplaceWordsInText(words, line)+"\n");
} finally {
if(in!=null) in.close(); //may throw IOException
return out.toString();
* Replaces all occurrences in text of each key in words with it's value.
* @returns String
private static String SearchAndReplaceWordsInText(Map words, String text) {
Iterator it = words.keySet().iterator();
while( it.hasNext() ) {
String key = (String)it.next();
text = text.replaceAll("\\b"+key+"\\b", (String)words.get(key));
return text;
* @returns: s with the first letter capitalized
String capitalize(String s)
return s.substring(0,0).toUpperCase() + s.substring(1);
}without what arguments?Without any arguments. If there are no arguments, there are no arguments of any kind. If you have a zoo with no animals in it, it's not meaningful to ask whether the animals which are not there are zebras or elephants.
does it prompt me to give it a text file name?Apparently.
when i run it this is all i get:
usage: Translate wordmapfile textfile
Press any key to continue...Right. And "wordmapfile" is almost certainly supposed to be a file that holds the word map, and "textfile" is almost certainly the file of text that it's going to translate. -
Reading multiple text files and writing them to one text file
Hi,
I'm trying to read a number of text files and write them to a single master file. My program reads all the files but only writes the last one to the master file.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// Input/Output Classes
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.GridLayout;
public class Actor implements ActionListener
public static String DataRoot = "I:\\JAVA\\UBP\\DAT
public static JFrame SW = new JFrame();
public static JTextField txtSPath;
public static JTextArea txtTable;
public void actionPerformed( ActionEvent e )
String Command = e.getActionCommand();
if (Command.equals("Process") )
SetupWin();
ProcessAll();
public void SetupWin()
SW.setTitle("void");
SW.setSize(300,400);
SW.setLayout(new GridLayout(6,1));
txtSPath = new JTextField(40); SW.add(txtSPath);
txtTable = new JTextArea(10, 40); SW.add(txtTable);
SW.setVisible(true);
public void ProcessAll()
Process("Dunstable","Finance");
Process("Dunstable","Production");
Process("Dunstable","Sales");
public void Process(String Town, String Dept)
String SPath = DataRoot + Town + "
" + Dept + ".txt";
String MPath = DataRoot + "masterFile" + ".txt";
txtSPath.setText(SPath);
String message = "Trying " + SPath;
System.out.println(message);
String SlaveTable=message;
try// if following fails an exception is thrown
Scanner Slave = new Scanner(new FileInputStream(SPath)); // reads slave file
PrintWriter outputStream = null;
outputStream = new PrintWriter(new FileOutputStream(MPath));
while ( Slave.hasNextLine() ) // reads text line by line
//Read and output next record
String PartRecord = Slave.nextLine();
String FullRecord = Town + " " + PartRecord;
System.out.println(FullRecord);
outputStream.println(FullRecord);
Slave.close();
outputStream.close();
txtTable.setText(SlaveTable);
//An Exception Error would be THROWN by above & CAUGHT below
catch(FileNotFoundException e)
message = "Could Not Find " + SPath;
System.out.println(message); //console
txtSPath.setText(message); //window
catch(IOException e)
System.out.println("Slave I/O Problem " + SPath);
}Edited by: Ardour on Mar 4, 2008 1:53 PMI haven't looked closely, but my spidey sense tingles at this:
new FileOutputStream(MPath)This will clobber (erase) the previous contents of the file. Open in append mode:
new FileOutputStream(MPath, true)Of course, if the file exists before you run this code, you will end up append to the original contents. If that is not wanted, consider using File's delete method first. -
Reading from a text file and displaying the contents with in a frame
Hi All,
I am trying to read some data from a text file and display it on a AWT Frame. The contents of the text file are as follows:
pcode1,pname1,price1,sname1,
pcode2,pname2,price2,sname1,
I am writing a method to read the contents from a text file and store them into a string by using FileInputStream and InputStreamReader.
Now I am dividing the string(which has the contents of the text file) into tokens using the StringTokenizer class. The method is as show below
void ReadTextFile()
FileInputStream fis=new FileInputStream(new File("nieman.txt"));
InputStreamReader isr=new InputStreamReader(fis);
char[] buf=new char[1024];
isr.read(buf,0,1024);
fstr=new String(buf);
String Tokenizer st=new StringTokenizer(fstr,",");
while(st.hasMoreTokens())
pcode1=st.nextToken();
pname1=st.nextToken();
price1=st.nextToken();
sname1=st.nextToken();
} //close of while loop
} //close of methodHere goes my problem: I am unable to display the values of pcode1,pname1,price1,sname1 when I am trying to access them from outside the ReadTextFile method as they are storing "null" values . I want to create a persistent string variable so that I can access the contents of the string variable from anywhere with in the java file. Please provide your comments for this problem as early as possible.
Thanks in advance.If pcode1,pname1,price1,sname1 are global variables, which I assume they are, then simply put the word static in front of them. That way, any class in your file can access those values by simply using this notation:
MyClassName.pcode1;
MyClassName.pname1;
MyClassName.price1;
MyClassName.sname1 -
Read Text file and count occurences of certain string
Hello,
I have a text file with lines of data in it. I would like to read this text file and count how many lines match a certain string of text.
For example my text file has this data in it.
dog,blue,big
dog,red,small
dog,blue,big
cat,blue,big
If the certain string of text is "dog,blue,big" then the count would return "2".
Thanks for your helpHello,
Thank you for your post.
I am afraid that the issue is out of support range of VS General Question forum which mainly discusses the usage issue of Visual Studio IDE such as
WPF & SL designer, Visual Studio Guidance Automation Toolkit, Developer Documentation and Help System
and Visual Studio Editor.
I am moving your question to the moderator forum ("Where is the forum for..?"). The owner of the forum will direct you to a right forum.
In addition, if you are working with Windows Forms app. please consult on Windows Forms Forum:http://social.msdn.microsoft.com/Forums/windows/en-US/home?category=windowsforms
If you are working with WPF app, please consult on WPF forum:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=wpf
If you are working with ASP.NET Web Application, I suggest that you can consult your issue on ASP.NET forum:
http://forums.asp.net/
for better solution and support.
Visual Studio Language Forums:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?category=vslanguages
Best regards,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.
Maybe you are looking for
-
Changing xwork-community-custom.xml file in Forums Application
Hi, could someone give me details on how to customize the file xwork-community-custom.xml, to override actions defined in xwork-community.xml? My problem in detail: I want to delete the "My questions" area in profile view, because we don´t have a "qu
-
How to store a file path in a TDMS Property
I need to store some Windows paths to other files as TDMS properties, but (according to another forum post I now can't find), the following characters are all illegal in TDMS properties: . : , ; ' \ @ < > # [ ] % ( ) { } | * ? = ! " Many of those are
-
Unable to Run SSIS Package Through SQL Agent Job
Hi, I recently upgraded SQL server 2008 R2 to SQL Server 2012. I also upgraded all the packages on the server. The package runs fine from BIDS. However when I try to run the package through the SQL Agent Job it fails with the error below: Executed as
-
Archlinux file searchplugin for firefox
save this as arch-file.xml (or a name of your choice) in your firefox searchplugins directory: <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/" xmlns:os="http://a9.com/-/spec/opensearch/1.1/"> <os:ShortName>ArchLinux File Search</os:
-
How to find url for a view of a bsp application in program?
hello all, I am devloping e-rec and am having a reqmnt, i want to knw how can i find a url for view view1 which is in bsp application zbsp. thanks, Reena