Take an existing text file and modify values
I’m looking to take an existing text file and modify certain values inside of it. Then save it to a new file, with all the same formatting as the original. The file format is not uniform and can change.
Basically the file is:
Random numbers and letters of unknown length for an unknown number of lines.
Label="Test_#"
Description
String
X=123
Y=456
Z=-789
20 lines of strings with numbers in them
Label="Test_#2"
Description
String
X=-1232
Y=4562
Z=7892
Then it repeats a set number of times.
I want to modify the X Y and Z = values for each Test_#.
I’ve managed to import the important values into a numeric array and I have a different array with values that will replace the existing ones. I’m having troubles replacing the existing ones. There are no zeros before or after the existing numbers so they are all different lengths.
If anyone has any sample code that does anything similar please post it. I’m sure someone has done something like this in the past.
Solved!
Go to Solution.
I just thought I would throw this out there. Can you make the .txt file tokenized? This would make searching for specific parameters much easier.
Reese, (former CLAD, future CLD)
Some people call me the Space Cowboy!
Some call me the gangster of love.
Some people call me MoReese!
...I'm right here baby, right here, right here, right here at home
Similar Messages
-
Reading a text file and transferring values into array
Hi,
I have a problem. So what I am trying to do is that, I read a text file and insert specific values from the text file into an array for future needs.
But I have to make sure that there is no duplicate entries. So thats what I have but, my method takes forever to finish...
here is my code:
String nomFichier = "Test_" + numTest + "_" + date + ".txt";
String ligne = "";
int z = 0;
int j = 0;
BufferedReader lecteurFichier = new BufferedReader(new FileReader(nomFichier));
while ((ligne = lecteurFichier.readLine()) != null) {
if (z > 3)
String valeur = "";
String dist = "";
boolean unique = true;
String [] chiffre = ligne.split(";");
if (intervalleAnalyser == 1)
valeur = chiffre[3];
dist = chiffre[4];
if (intervalleAnalyser == 2)
valeur = chiffre[2];
dist = chiffre[4];
if (intervalleAnalyser == 3)
valeur = chiffre[1];
dist = chiffre[4];
if (z == 4) {
intervalleDiagramme[j] = valeur;
j++;
if (z > 4) {
for (int i = 0; i < intervalleDiagramme.length; i++)
for (int x = 0; x < i; x++)
if(intervalleDiagramme[i] == intervalleDiagramme[x])
unique = false;
if (unique)
intervalleDiagramme[j] = valeur;
j++;
z++;
lecteurFichier.close(); // toujours fermer le fichierHi,
Thanks for your reply,
1) Yeah I have a method that asks the question and assigns it to a variable.
2) Well the z will stop once there is no lines to read no?
for the set.add(), I am not that familar...
I changed bit a code and I have this now:
if (z > 4) {
for (int i = 0; i < intervalleDiagramme.length; i++)
System.out.println(intervalleDiagramme);
if(intervalleDiagramme[i].equals(valeur))
System.out.println(intervalleDiagramme[i] + " " + valeur);
unique = false;
if (unique)
intervalleDiagramme[j] = valeur;
EDIT:
I figured a way to assign " " to all the values in my array. But I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 380
at TP3.lireFichier(TP3.java:305)
And my line 305 is: intervalleDiagramme[j] = valeur;
EDIT2:
So ok I found my mistake and corrected it. But I want to know is there a way of doing this without setting the size of the array? because sometimes there needs to be 21 values sometimes 19 and sometimes 20....
If I take out: = new String [21] out I get a NullPointer error...
Edited by: Ara1992Habs on Dec 13, 2009 7:29 AM
Edited by: Ara1992Habs on Dec 13, 2009 7:37 AM -
Hi All,
powershell script Method required to read a value from registry and then taking the backup of that values in some text file.
For example the hive is
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path
and under path i need to take back up of values in some text file and then put some value in the registry after back is taken in text file.
Also how to read the text file values so that we can again write to registry hive back from the back up text file.
Your help is much appreciated.
Umeed4uI think you need to read this first:
http://social.technet.microsoft.com/Forums/scriptcenter/en-US/a0def745-4831-4de0-a040-63b63e7be7ae/posting-guidelines?forum=ITCG
Don't retire TechNet! -
(Don't give up yet - 12,830+ strong and growing) -
Compare data from 2 text files and output match
Hi all,
I need some advice.
Firstly in BinaryCode.txt the data is as such:
Replace BinaryCode0 1 0 0 0 0 0 0 0 0
Replace BinaryCode0 1 0 0 0 0 0 0 0 1
Replace BinaryCode1 1 1 1 0 1 1 1 1 1
Replace BinaryCode1 1 0 0 0 0 0 0 0 0
the first line in the text file is the header. So I need to check if the names in the second column (BinaryCode0 or BinaryCode1)appear in the Timed_Sets.txt file.
The data in Timed_Sets.txt is as such:
BinaryCode0,6,40,.........................
BinaryCode0,7,40,.........................
BCName1,0,20,.............................
BCName1,1,20,.............................
For example since BinaryCode0 is a match I will output the entire row in Timed_Set.txt to another array.
I have been working on a program but I don't get the expected output.
The text files and the VI are attached.
I appreciate your kind assistance in the matter.
Thank You
Regards
kart
Solved!
Go to Solution.
Attachments:
BinaryCode.txt 1 KB
compare text files.vi 15 KB
Timed_Sets.txt 2 KBIf I understood correctly what the output should be then what you basically need to do is to walk through the column in BinaryCode.txt and for each unique value pull out the corresponding rows from Timed_Sets.txt. There's a variety of ways to do this, depending on how much data you have and whether or not you can use any kind of prior knowledge as to the actual file content (such as the names of the keys being searched). Attached is one way. Modify as needed.
Attachments:
compare text files MOD.vi 27 KB -
To add meta tags, you open your published .html pages with TextEdit or any other text editor and modify as required. You have to do redo it each time you republish. I need step by step instructions on how to accomplish this please .
Rage Sitemap Automator and iWeb SEO Tool are two different applications.
Use SEO Tool to add the title tag and meta description. These need to be added to the html file for every page of your website. SEO Tool stores all these so that when you republish you only need to add tags to any new pages and click the re-apply button to refresh the existing ones.
Once you have added. refreshe the tags with iWeb SEO Tool and uploaded the files with your FTP application, then open the site in Sitemap Automator and create and upload a new sitemap.
Once you have set up accounts with Google, Yahoo and Bing, verified your site with each and submitted a sitemap, on subsequent publishing Sitemap Automator will resubmit the sitemap with one button click. It will also notify Ask.com whch doesn't require an account since you can add your domain name to this URL to ping them...
http://submissions.ask.com/ping?sitemap=http%3A//www.domain.com/sitemap.xml -
Read a text file and populate table
My email addres is [email protected]
I am new to java. My project requires me to read a text file and pick some values from the text file and populate a table in MS Access. The main fields are from the TEXT. Some of the columns to be read are:
Transaction ref.
Amount
User ref.
Date
The text file is as follows:
Receiver =
FBNINGLAXXX LT : A
FST BANK OF NIGERIA PLC
LAGOS
LAGOS
NG
NIGERIA
Transaction ref. = SPLOUK01P0008888 Related ref. = 00077003
Amount = 16675750, NGN Value/Date =
Format & Validation
Version = 0205 Checked = Minimum
Netw. Appl. = FIN Passed = Minimum
Sender to Receiver Instructions
Banking Prior. = User ref. = SPLOUK01P0008888
Warning Status =
Possible Duplicate Emission
Appl/Serv = SWIFT Interface
RP & Ft = SIfrom_SWIFT
Date/Time = 01/04/03 18:53:19
Text =
:20:SPLOUK01P0008888
:28D:1/1
:30:030401
:21:00077003
:32B:NGN16675750,00
:50H:/4072010014877
SPDC FBN East Main A/C
:57D:WEMA BANK PLC
PLOT 22 TRANS-AMADI BRANCH P.H.
PORT HARCOURT.
RIVERS STATE.
:59:/0421002101818
PROJECT MASTERS NIGERIA LTD.
C101 ELIOGBOLO VILLAGE OFF
EAST-WEST ROAD RUMUOKORO PORT HAR
COURT
:70:PM PCE-TS 03 001030226
:71A:OUR
Block 5:
{MAC:9F664844}{CHK:60EF6513E579}
Message History =
*Original (Completed)See in this case as you are dealing with Files and database. you need read the File by using the I/O Streams. if you have to select some particular values you can go Random access file.Once you have retrived values. You can go for the second part that is make a jdbc connection to database, and use simple SQL statements to populate those values into the table.
How this will give you a better picture -
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. -
Issue : Read a text file and print the same
Hi, My requirement is to read a text file and print it the same way.
import java.io.BufferedReader;
import java.io.FileReader;
public class CatFile {
public static void main(String[] args) throws Exception
FileReader file = new FileReader("D:/Test/Allfiles.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null)
text += line;
line = reader.readLine();
System.out.println(text);
The text file i used contains
A
B
C
but my output is ABC.
What change should be made to print it the same way in the txt file ?Hi EJP,
I modified the code based on your suggestion and now its working as expected. Thanks
Modified code :
import java.io.BufferedReader;
import java.io.FileReader;
public class CatFile {
public static void main(String[] args) throws Exception
FileReader file = new FileReader("D:/Test/Allfiles.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null)
System.out.println(line);
line = reader.readLine();
text += line;
} -
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 -
Searching a text file and printing the line if found!
Hi, Im fairly new to JAVA and have been googling this for hours and havent found any results that
have helped me...
Im looking to search a text file for a value that is in a that is delimited by colons
eg 45787 : 398948 : 398884 : 398984
IF that value is found I need to print this entire line and move it into a string.
I can work out the delimit part, the problem for me is a)searching the text file
and b) tell java to print that line only??
Any help would be very very much appreciated
Cheers
Jamespublic void printCourses() throws Exception
stuinput[] courseObjArray = new stuinput[10]; //Make sure this is the same as the ammount in the text
Scanner sc = new Scanner(new File("testfile.txt"));
int i=0;
boolean found = false;
while(sc.hasNextLine())
//Delimit this line with scanner
Scanner sc1 = new Scanner(sc.nextLine());
sc1.useDelimiter(":");
courseObjArray[i] = new stuinput(sc1.next(),sc1.next());
i++;
}//while
for(int i1 = 0;i1 < courseObjArray.length;i1++)
System.out.println(courseObjArray[i1].courseCode);
System.out.println(courseObjArray[i1].courseName);
System.out.println(courseObjArray[i1].courseName);
System.out.println("-----------------");
String courseCode2 = "courseObjArray[i1].courseCode";
if (courseCode2 == "12345")
System.out.println("working");
else{System.out.println("Not Found");}
}hmmm just wondering why could this method always return a "Not Found"....if the text file had a whole bunch of values like this
12345:Course1
12344:Course2
12343:Course3
isnt it surposed to return 1 "Working"?? because there is a 12345 in on of the line, in the semi colon delimited line with 2 values, one being the course code, one being the course name??
Given that there is 10 lines (from Array Object) -
Hi i am new to labview
I want to extract data from a text file and display it on the front panel.
How do i proceed??
I have attached a file for your brief idea...
Attachments:
extract.jpg 3797 KBRoopeshV wrote:
Hi,
The below code shows how to read from txt file and display in the perticular fields.
Why have you used waveform?
Regards,
Roopesh
There are so many things wrong with this VI, I'm not even sure where to start.
Hard-coding paths that point to your user folder on the block diagram. What if somebody else tries to run it? They'll get an error. What if somebody tries to run this on Windows 7? They'll get an error. What if somebody tries to run this on a Mac or Linux? They'll get an error.
Not using Read From Spreadsheet File.
Use of local variables to populate an array.
Cannot insert values into an empty array.
What if there's a line missing from the text file? Now your data will not line up. Your case structure does handle this.
Also, how does this answer the poster's question? -
Reading a text file and putting it in a textarea
hi can u tell me how to read a text file and display the contents in a text area using jsp please?
thanks :o)<%@ page import="java.sql.*, java.io.*" %>
<HTML>
<HEAD>
<TITLE>User Application Area</TITLE>
<SCRIPT LANGUAGE="javascript" SRC="cal2.js">
</SCRIPT>
<SCRIPT LANGUAGE="javascript" SRC="cal_conf2.js"></SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:fypproject","","");
Statement st = con.createStatement();
String email = (String)session.getAttribute("email");
String levelStatus = (String)session.getAttribute("levelStatus");
String details = "SELECT PD.Forename, PD.Surname, L.Level_Name FROM Personal_Details PD,
Login_Details LD, Levels L WHERE PD.Email_Address = '" + email + "' AND PD.Email_Address =
LD.Email_Address AND LD.Level_ID = '" + levelStatus + "' AND LD.Level_ID = L.Level_ID";
ResultSet rsDet = st.executeQuery(details);
if(rsDet.next()) {
String forename = rsDet.getString("Forename");
String surname = rsDet.getString("Surname");
String levelName = rsDet.getString("Level_Name");
%>
<DIV ALIGN="center"><H1>User Application Arena</H1></DIV>
<BR>
<H4>Welcome back <% out.println(forename + " " + surname); %> </H4>
<BR>
Your status is:
<FONT COLOR = "red">
<% out.println(levelName); %>
</FONT>
<BR>
<%
if(levelStatus.compareTo("0")==0) {
%>
<BR>
<DIV ALIGN="center">
Please come back later and re-check your status to see if your application has progressed. If it has
been more than a week since you submitted it please phone the HR department on 020 7123 4567
<BR><BR>
Log Out
</DIV>
</FORM>
<%
else if(levelStatus.compareTo("1")==0) {
%>
<FORM NAME="sampleform" ACTION="ProcessInterview.jsp">
<DIV ALIGN="center">
Congratulations, we would like to invite you for a First Round tests and interview. Please select a
date that would suit you on our online calendar below
<BR><BR>
<SMALL>PLEASE CLICK HERE TO SELECT A DATE</SMALL>
<BR><BR>
<INPUT TYPE="text" NAME="firstinput" SIZE=20>
<BR><BR>
<INPUT TYPE="submit" VALUE="Confirm">
</DIV>
</FORM>
<%
else if(levelStatus.compareTo("2")==0) {
%>
<FORM NAME="sampleform" ACTION="ProcessInterview.jsp">
<DIV ALIGN="center">
Congratulations, we would like to invite you for a Second Round interview. Please select a date that
would suit you on our online calendar below
<BR><BR>
<SMALL>PLEASE CLICK HERE TO SELECT A DATE</SMALL>
<BR><BR>
<INPUT TYPE="text" NAME="firstinput" SIZE=20>
<BR><BR>
<INPUT TYPE="submit" VALUE="Confirm">
</DIV>
</FORM>
<%
else if(levelStatus.compareTo("3")==0) {
File inFile = new File("offer.txt");
StringBuffer sb = new StringBuffer();
BufferedReader buf = new BufferedReader(new FileReader(inFile));
while (buf.ready()) {
sb.append(buf.readLine());
buf.close();
%>
<TEXTAREA NAME ="text" ROWS="10" COLS="60">
<%= sb.toString() %>
</TEXTAREA>
<%
else if(levelStatus.compareTo("4")==0) {
out.println("send rej email");
st.close();
con.close();
%>
</BODY>
</HTML>
THANKS!! :o) -
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 -
Hello All,
anybody have a procedure to open a XML file and modify some os that tags and after save it at a local file or a server?
Best Regards,
RicardoRicardo,
Take a look at this simple transformation example,
http://help.sap.com/abapdocu_70/en/ABENABAP_ST_EXAMPLE.htm
http://wiki.sdn.sap.com/wiki/display/Snippets/XMLXLStransformation
http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/a89312f8-0b01-0010-86b3-fdd7178e0534
Last, but not least take a look at the blog series here in SDN.. He has a five part series for XML processing in ABAP...
/people/tobias.trapp/blog/2005/05/04/xml-processing-in-abap-part-1
Maybe you are looking for
-
How do I create a new document in adobe?
How do I create a new document in adobe?
-
I've lost my hue/saturation screen in photoshop. How do I get it back?
I've lost my hue/saturation screen in photoshop. How do I get it back?
-
Hi folks, I need your help to recreate a organizational unit ID. By mistake we have deleted a buyer set up from SRM org structure. Instead of deleting the buyer's positoin we have deleted also the buyer's org ID. Because of that we couldn't display t
-
Maximum connections allowed for AMS 5.0.1
How can I find out the maximum connection allowed for adobe media server 5.0.1 standard license?
-
Module Pool Programming - noninput screen
Hi Folks, I have a requirement where i need to have check box.When check box is checked screen fields should be enabled else it should be disabled. Please suggest me. If the checkbox is checked fields should become mandatory. Please suggest