Adding a column after parsing a info from a text file
I use the following script to get info from "User Rights Assignment" security policy. This outputs the policy and the security settings with all the accounts listed. How can I add another column to the output to say, if one of the accounts
value for a policy contains a domain account output "Domain Account"
$temp = "c:\"
$file = "$temp\privs.txt"
[string] $readableNames
$outhash = @{}
$process = [diagnostics.process]::Start("secedit.exe", "/export /cfg $file /areas USER_RIGHTS")
$process.WaitForExit()
$in = get-content $file
foreach ($line in $in) {
if ($line.StartsWith("Se")) {
$privilege = $line.substring(0,$line.IndexOf("=") - 1)
switch ($privilege){
"SeCreateTokenPrivilege " {$privilege = "Create a token object"}
"SeAssignPrimaryTokenPrivilege" {$privilege = "Replace a process-level token"}
"SeLockMemoryPrivilege" {$privilege = "Lock pages in memory"}
"SeIncreaseQuotaPrivilege" {$privilege = "Adjust memory quotas for a process"}
"SeUnsolicitedInputPrivilege" {$privilege = "Load and unload device drivers"}
"SeMachineAccountPrivilege" {$privilege = "Add workstations to domain"}
"SeTcbPrivilege" {$privilege = "Act as part of the operating system"}
"SeSecurityPrivilege" {$privilege = "Manage auditing and the security log"}
"SeTakeOwnershipPrivilege" {$privilege = "Take ownership of files or other objects"}
"SeLoadDriverPrivilege" {$privilege = "Load and unload device drivers"}
"SeSystemProfilePrivilege" {$privilege = "Profile system performance"}
"SeSystemtimePrivilege" {$privilege = "Change the system time"}
"SeProfileSingleProcessPrivilege" {$privilege = "Profile single process"}
"SeCreatePagefilePrivilege" {$privilege = "Create a pagefile"}
"SeCreatePermanentPrivilege" {$privilege = "Create permanent shared objects"}
"SeBackupPrivilege" {$privilege = "Back up files and directories"}
"SeRestorePrivilege" {$privilege = "Restore files and directories"}
"SeShutdownPrivilege" {$privilege = "Shut down the system"}
"SeDebugPrivilege" {$privilege = "Debug programs"}
"SeAuditPrivilege" {$privilege = "Generate security audit"}
"SeSystemEnvironmentPrivilege" {$privilege = "Modify firmware environment values"}
"SeChangeNotifyPrivilege" {$privilege = "Bypass traverse checking"}
"SeRemoteShutdownPrivilege" {$privilege = "Force shutdown from a remote system"}
"SeUndockPrivilege" {$privilege = "Remove computer from docking station"}
"SeSyncAgentPrivilege" {$privilege = "Synchronize directory service data"}
"SeEnableDelegationPrivilege" {$privilege = "Enable computer and user accounts to be trusted for delegation"}
"SeManageVolumePrivilege" {$privilege = "Manage the files on a volume"}
"SeImpersonatePrivilege" {$privilege = "Impersonate a client after authentication"}
"SeCreateGlobalPrivilege" {$privilege = "Create global objects"}
"SeTrustedCredManAccessPrivilege" {$privilege = "Access Credential Manager as a trusted caller"}
"SeRelabelPrivilege" {$privilege = "Modify an object label"}
"SeIncreaseWorkingSetPrivilege" {$privilege = "Increase a process working set"}
"SeTimeZonePrivilege" {$privilege = "Change the time zone"}
"SeCreateSymbolicLinkPrivilege" {$privilege = "Create symbolic links"}
"SeDenyInteractiveLogonRight" {$privilege = "Deny local logon"}
"SeRemoteInteractiveLogonRight" {$privilege = "Allow logon through Terminal Services"}
"SeServiceLogonRight" {$privilege = "Logon as a service"}
"SeIncreaseBasePriorityPrivilege" {$privilege = "Increase scheduling priority"}
"SeBatchLogonRight" {$privilege = "Log on as a batch job"}
"SeInteractiveLogonRight" {$privilege = "Log on locally"}
"SeDenyNetworkLogonRight" {$privilege = "Deny Access to this computer from the network"}
"SeNetworkLogonRight" {$privilege = "Access this Computer from the Network"}
$sids = $line.substring($line.IndexOf("=") + 1,$line.Length - ($line.IndexOf("=") + 1))
$sids = $sids.Trim() -split ","
$readableNames = ""
foreach ($str in $sids){
$str = $str.substring(1)
$sid = new-object System.Security.Principal.SecurityIdentifier($str)
$readableName = $sid.Translate([System.Security.Principal.NTAccount])
$readableNames = $readableNames + $readableName.Value + ", "
$outhash.Add($privilege,$readableNames.substring(0,($readableNames.Length - 1)))
(foreach {$outhash.getenumerator() | select Name, Value | sort name})
remove-item c:\privs.txt
Hi Sergio,
To combine the outputs, please use "PSobject" and try the script below, please also note I haven't tested:
$output=@()
$temp = "c:\"
$file = "$temp\privs.txt"
[string] $readableNames
$process = [diagnostics.process]::Start("secedit.exe", "/export /cfg $file /areas USER_RIGHTS")
$process.WaitForExit()
$in = get-content $file
foreach ($line in $in) {
if ($line.StartsWith("Se")) {
$privilege = $line.substring(0,$line.IndexOf("=") - 1)
switch ($privilege){
"SeCreateTokenPrivilege " {$privilege = "Create a token object"}
"SeAssignPrimaryTokenPrivilege" {$privilege = "Replace a process-level token"}
"SeLockMemoryPrivilege" {$privilege = "Lock pages in memory"}
"SeIncreaseQuotaPrivilege" {$privilege = "Adjust memory quotas for a process"}
"SeUnsolicitedInputPrivilege" {$privilege = "Load and unload device drivers"}
"SeMachineAccountPrivilege" {$privilege = "Add workstations to domain"}
"SeTcbPrivilege" {$privilege = "Act as part of the operating system"}
"SeSecurityPrivilege" {$privilege = "Manage auditing and the security log"}
"SeTakeOwnershipPrivilege" {$privilege = "Take ownership of files or other objects"}
"SeLoadDriverPrivilege" {$privilege = "Load and unload device drivers"}
"SeSystemProfilePrivilege" {$privilege = "Profile system performance"}
"SeSystemtimePrivilege" {$privilege = "Change the system time"}
"SeProfileSingleProcessPrivilege" {$privilege = "Profile single process"}
"SeCreatePagefilePrivilege" {$privilege = "Create a pagefile"}
"SeCreatePermanentPrivilege" {$privilege = "Create permanent shared objects"}
"SeBackupPrivilege" {$privilege = "Back up files and directories"}
"SeRestorePrivilege" {$privilege = "Restore files and directories"}
"SeShutdownPrivilege" {$privilege = "Shut down the system"}
"SeDebugPrivilege" {$privilege = "Debug programs"}
"SeAuditPrivilege" {$privilege = "Generate security audit"}
"SeSystemEnvironmentPrivilege" {$privilege = "Modify firmware environment values"}
"SeChangeNotifyPrivilege" {$privilege = "Bypass traverse checking"}
"SeRemoteShutdownPrivilege" {$privilege = "Force shutdown from a remote system"}
"SeUndockPrivilege" {$privilege = "Remove computer from docking station"}
"SeSyncAgentPrivilege" {$privilege = "Synchronize directory service data"}
"SeEnableDelegationPrivilege" {$privilege = "Enable computer and user accounts to be trusted for delegation"}
"SeManageVolumePrivilege" {$privilege = "Manage the files on a volume"}
"SeImpersonatePrivilege" {$privilege = "Impersonate a client after authentication"}
"SeCreateGlobalPrivilege" {$privilege = "Create global objects"}
"SeTrustedCredManAccessPrivilege" {$privilege = "Access Credential Manager as a trusted caller"}
"SeRelabelPrivilege" {$privilege = "Modify an object label"}
"SeIncreaseWorkingSetPrivilege" {$privilege = "Increase a process working set"}
"SeTimeZonePrivilege" {$privilege = "Change the time zone"}
"SeCreateSymbolicLinkPrivilege" {$privilege = "Create symbolic links"}
"SeDenyInteractiveLogonRight" {$privilege = "Deny local logon"}
"SeRemoteInteractiveLogonRight" {$privilege = "Allow logon through Terminal Services"}
"SeServiceLogonRight" {$privilege = "Logon as a service"}
"SeIncreaseBasePriorityPrivilege" {$privilege = "Increase scheduling priority"}
"SeBatchLogonRight" {$privilege = "Log on as a batch job"}
"SeInteractiveLogonRight" {$privilege = "Log on locally"}
"SeDenyNetworkLogonRight" {$privilege = "Deny Access to this computer from the network"}
"SeNetworkLogonRight" {$privilege = "Access this Computer from the Network"}
$sids = $line.substring($line.IndexOf("=") + 1,$line.Length - ($line.IndexOf("=") + 1))
$sids = $sids.Trim() -split ","
$readableNames = ""
foreach ($str in $sids){
$str = $str.substring(1)
$sid = new-object System.Security.Principal.SecurityIdentifier($str)
$readableName = $sid.Translate([System.Security.Principal.NTAccount])
$readableNames = $readableNames + $readableName.Value + ", "
$output += New-Object PSObject -Property @{
privilege = $privilege
readableNames = $readableNames.substring(0,($readableNames.Length - 1))
#else = $line."property" }
$output
To use PSobject, this article for your reference:
New-Object PSObject –Property [HashTab
If you have any feedback on our support,
please click here.
Best Regards,
Anna Wang
TechNet Community Support
Similar Messages
-
How to parse data from a text file with no convenient delimiters?
I need to read data from a text file. This file contains one line of data with the repeating pattern "time 00 ADVar2: ___ Height: ____ time 01 ADVar2: ___ Height: ___ ..." I need LabView to parse out the "time" and "height" values, build an array with the values, and graph the correlation on an X&Y plot. Does Labview have an automated way to read to the input data file and parse out the correct values, even without convenient delimiters? Thank you.
You actually do have a convenient delimiter: "time". Thus, you can make an array using that as the delimiter. Only caveat is that the first array element will be empty. Then you can conveniently use the Scan From String function in a for-loop. Something like this:
Message Edited by smercurio_fc on 11-21-2008 03:13 PM
Attachments:
Example_VI.png 9 KB -
Is there a way where i can parse a method, or conditional statement from a text file? Like lets say that i had the statement in Test.txt
if(X >= Y)
do something
}and X and Y are already defined in the java file, is there a way that i could parse it so that the java code invokes it, as if it were part of the java file?Here's a little Groovy demo:
import groovy.lang.GroovyShell;
* To run this demo,
* - download 'groovy-binary-1.5.5.zip': http://dist.groovy.codehaus.org/distributions/groovy-binary-1.5.5.zip
* - unzip, and add 'lib/groovy-all-1.5.5.jar' to your classpath
public class GroovyDemo {
public static void main(String[] args) throws Exception {
String script =
" if(X > Y) { \n"+
" return X+X \n"+
" } else { \n"+
" return Y/4 \n"+
" } \n";
System.out.println("script=\n"+script);
GroovyShell shell = new GroovyShell();
shell.setProperty("X", new Integer(10));
shell.setProperty("Y", new Integer(9));
Object value = shell.evaluate(script);
System.out.println("value="+value+", "+value.getClass());
shell.setProperty("X", new Integer(8));
value = shell.evaluate(script);
System.out.println("value="+value+", "+value.getClass());
/* output:
script=
if(X > Y) {
return X+X
} else {
return Y/4
value=20, class java.lang.Integer
value=2.25, class java.math.BigDecimal
*/ -
Adding data from a text file into a JTextArea
I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?
then you need to be more specific in what you need help with because those are two commonly used options for reading data in from a file. what have you tried? where is your code failing? what kind of errors are you getting? of course it looks like others in the forum have already reprimanded you for failing to post properly.
i have used both FileReader and the nio package for cfg and ini files which are both just txt files as well as massive data files. so tell me how they dont help you? -
How to input data into an arraylist from a text file?
I am trying to take data from a text file and put that data into an arraylist. First here is the text file:
[item1, 10, 125.0, item2, 10, 12.0, item3, 20, 158.0]
3
4530.0
[item5, 65, 555.5, item4, 29, 689.0]
2
56088.5
[item7, 84, 34.5, item6, 103, 0.5, item8, 85, 1.36]
3
3065.1The text between the [ ] is the output from my arraylists. I have three arraylists. The first [ ] belongs to arraylist A, the second to arraylist B, and the third to arraylist C. The format of the arraylists is this:
<item name>,<# in stock>,<value of one item>
The first number below the arraylists in the text file represents the number of items in the list. The second number below the arraylists represents the total value of the items in the arraylists.
Here is the class file I have (yes, it does everything):
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Inventory extends Object
public int toAdd = 0;
private boolean done = false; //Are we done yet?
public String strItemName; //The name of the item type.
public int intNumInStock; //The number in stock of that type.
public double dblValueOfOneItem; //The value of one item.
public String strNumberInStock;
public double dblTotalValueA; //The total value of warehouse A.
public double dblTotalValueB; //The total value of warehouse B.
public double dblTotalValueC; //The total value of warehouse C.
public int intWarehouseAItemCount; //Counter for items in warehouse A.
public int intWarehouseBItemCount; //Counter for items in warehouse B.
public int intWarehouseCItemCount; //Counter for items in warehouse C.
ArrayList warehouseAList = new ArrayList(); //Create the Warehouse A ArrayList.
ArrayList warehouseBList = new ArrayList(); //Create the Warehouse B arrayList.
ArrayList warehouseCList = new ArrayList(); //Create the Warehouse C arrayList.
/** Construct a new Inventory object. */
public Inventory()
super();
/**Add items to the Warehouse A ArrayList.*/
private void createWareHouseA()
System.out.println("!" + toAdd + " item types will be added to warehouse A.");
//Cast
String strNumInStock = Integer.toString(intNumInStock);
String strValueOfOneItem = Double.toString(dblValueOfOneItem);
this.strNumberInStock = strNumInStock;
System.out.println("!Initial size of warehouseAList : " +
warehouseAList.size());
//Add items to the array List
warehouseAList.add(this.strItemName);
warehouseAList.add(this.strNumberInStock);
warehouseAList.add(this.dblValueOfOneItem);
System.out.println("!size of arrayList after additions " + warehouseAList.size());
/**Add items to the Warehouse B ArrayList.*/
private void createWareHouseB()
System.out.println("!" + toAdd + " item types will be added to warehouse B.");
//Cast
String strNumInStock = Integer.toString(intNumInStock);
String strValueOfOneItem = Double.toString(dblValueOfOneItem);
this.strNumberInStock = strNumInStock;
System.out.println("!Initial size of warehouseBList : " +
warehouseBList.size());
//Add items to the array List
warehouseBList.add(this.strItemName);
warehouseBList.add(this.strNumberInStock);
warehouseBList.add(this.dblValueOfOneItem);
System.out.println("!size of arrayList after additions " + warehouseBList.size());
/**Add items to the Warehouse C ArrayList.*/
private void createWareHouseC()
System.out.println("!" + toAdd + " item types will be added to warehouse C.");
//Cast
String strNumInStock = Integer.toString(intNumInStock);
String strValueOfOneItem = Double.toString(dblValueOfOneItem);
this.strNumberInStock = strNumInStock;
System.out.println("!Initial size of warehouseCList : " +
warehouseCList.size());
//Add items to the array List
warehouseCList.add(this.strItemName);
warehouseCList.add(this.strNumberInStock);
warehouseCList.add(this.dblValueOfOneItem);
System.out.println("!size of arrayList after additions " + warehouseCList.size());
/**Interpret the commands entered by the user.*/
public void cmdInterpreter()
this.displayHelp();
Scanner cin = new Scanner(System.in);
while (!this.done)
System.out.print(">");
//"line" equals the next line of input.
String line = cin.nextLine();
this.executeCmd(line);
/**Execute one line entered by the user.
* @param cmdLN; The command entered by the user to execute. */
private void executeCmd(String cmdLN)
Scanner line = new Scanner(cmdLN);
if (line.hasNext())
String cmd = line.next();
//What to do when users enter the various commands below.
if (cmd.equals("help"))
this.displayHelp();
else if (cmd.equals("Q!"))
this.done = true;
else if (cmd.equals("F") && line.hasNext())
this.inputFromFile(line.next());
else if (cmd.equals("K") && line.hasNext())
int numItemsToAdd = Integer.valueOf( line.next() ).intValue();
this.toAdd = numItemsToAdd;
this.inputFromKeyboard(numItemsToAdd);
/**What to do if input comes from a file.
* @param inputFile; The name of the input file to process.*/
private void inputFromFile(String inputFile)
Scanner cin = new Scanner(System.in);
System.out.println("!Using input file " + inputFile + ".");
System.out.print("!Enter the name of the output file: ");
String outputFile = cin.next();
System.out.println("!Using output file " + outputFile + ".");
try
BufferedReader in = new BufferedReader(new FileReader(inputFile));
//Scanner in = new Scanner(new File(inputFile));
//Initialize the String variables.
String line1 = null;
String line2 = null;
String line3 = null;
String line4 = null;
String line5 = null;
String line6 = null;
String line7 = null;
String line8 = null;
String line9 = null;
System.out.println(in.equals(",") + " see?");
//System.out.println((char)(char)in.read() + " experiment");
/**This loop assigns values to the string variables based on the
* values on each line in the input file. */
while(in.readLine() != null)
line1 = in.readLine();
line2 = in.readLine();
line3 = in.readLine();
line4 = in.readLine();
line5 = in.readLine();
line6 = in.readLine();
line7 = in.readLine();
line8 = in.readLine();
line9 = in.readLine();
//Print the contents of each line in the input file.
System.out.println("!value of line 1: " + line1);
System.out.println("!value of line 2: " + line2);
System.out.println("!value of line 3: " + line3);
System.out.println("!value of line 4: " + line4);
System.out.println("!value of line 5: " + line5);
System.out.println("!value of line 6: " + line6);
System.out.println("!value of line 7: " + line7);
System.out.println("!value of line 8: " + line8);
System.out.println("!value of line 9: " + line9);
/**Add items to the warehouses.*/
warehouseAList.add(line1);
warehouseBList.add(line4);
warehouseCList.add(line7);
/**Add the item count and total value for warehouse A.*/
int intLine2 = Integer.valueOf(line2).intValue();
this.intWarehouseAItemCount = intLine2;
double dblLine3 = Double.valueOf(line3).doubleValue();
this.dblTotalValueA = dblLine3;
/**Add the item count and total value for warehouse B.*/
int intLine5 = Integer.valueOf(line5).intValue();
this.intWarehouseBItemCount = intLine5;
double dblLine6 = Double.valueOf(line6).doubleValue();
this.dblTotalValueB = dblLine6;
/**Add the item count and total value for warehouse C.*/
int intLine8 = Integer.valueOf(line8).intValue();
this.intWarehouseCItemCount = intLine8;
double dblLine9 = Double.valueOf(line9).doubleValue();
this.dblTotalValueC = dblLine9;
/**Ask the user how many items to add or delete from inventory.*/
System.out.print("Enter the number to add to inventory for " +
warehouseAList.get(0) + ":");
String toAddOrDel = cin.next();
/**Print the contents of all the warehouses. */
System.out.println(" ");
//Print the contents of warehouse A.
System.out.println("!--------------------------------");
System.out.println("!----------Warehouse A:----------");
System.out.println("!--------------------------------");
//Print the item list for warehouse A.
System.out.println(warehouseAList);
//Print the total amount of items in warehouse A.
System.out.println("Total items: " + this.intWarehouseAItemCount);
//Print the total value of the items in warehouse A.
System.out.println("Total value: " + this.dblTotalValueA);
System.out.println("!--------------------------------");
System.out.println("!----------Warehouse B:----------");
System.out.println("!--------------------------------");
//Print the item list for warehouse B.
System.out.println("!warehouseB: " + warehouseBList);
//Print the total amount of items in warehouse B.
System.out.println("Total items: " + this.intWarehouseBItemCount);
//Print the total value of the items in warehouse B.
System.out.println("Total value: " + this.dblTotalValueB);
System.out.println("!--------------------------------");
System.out.println("!----------Warehouse C:----------");
System.out.println("!--------------------------------");
//Print the item list for warehouse C.
System.out.println("!warehouseC: " + warehouseCList);
//Print the total amount of items in warehouse C.
System.out.println("Total items: " + this.intWarehouseCItemCount);
//Print the total value of the items in warehouse C.
System.out.println("Total value: " + this.dblTotalValueC);
in.close();
catch (FileNotFoundException e)
System.out.println("!Error: Unable to open file for reading.");
catch (EOFException e)
System.out.println("!Error: EOF encountered, file may be corrupted.");
catch (IOException e)
System.out.println("!Error: Cannot read from file.");
/**What to do if input comes from the keyboard.
* @param numItems; The total number of items that will be added to the
* Warehouse(s). */
public void inputFromKeyboard(int numItems)
System.out.println("!You will be adding " + numItems + " items to " +
"inventory from the keyboard. ");
this.toAdd = numItems;
Scanner cin = new Scanner(System.in);
//Prompt user for name of output file.
System.out.print("!Enter the name of the output file: ");
String outputFile = cin.next();
/**This loop asks the user for information about the item(s) and inputs
*them into the appropriate array.*/
int count = 0;
while (numItems > count)
//Item name.
System.out.print("!Item name: ");
String addItemName = cin.next();
//Number in stock.
System.out.print("!Number in stock: ");
String addNumInStock = cin.next();
//Initial warehouse.
System.out.print("!Initial warehouse(A,B,C): ");
String addInitWarehouse = cin.next();
//Value of one item.
System.out.print("!Value of one item: ");
String addValueOfOneItem = cin.next();
//Add or delete from inventory
System.out.print("!Enter amount to add or delete from inventory: ");
String strAddOrDelete = cin.next();
System.out.println("!Amount to add or delete: " + strAddOrDelete);
//Cast
int intAddNumInStock = Integer.valueOf(addNumInStock).intValue();
double doubleAddValueOfOneItem = Double.valueOf(addValueOfOneItem).doubleValue();
int intAddOrDelete = Integer.valueOf(strAddOrDelete).intValue();
/**Add intAddNumInStock with intAddOrDelete to determine the amount
* to add or delete from inventory (If a user wishes to remove items
* from inventory simply add negative values). */
intAddNumInStock = intAddNumInStock + intAddOrDelete;
System.out.println("!Inventory after modifications: " + strAddOrDelete);
this.strItemName = addItemName;
this.intNumInStock = intAddNumInStock;
this.dblValueOfOneItem = doubleAddValueOfOneItem;
//Put items into warehouse A if appropriate.
if (intAddNumInStock < 25)
//Increment the warehouse A item count.
this.intWarehouseAItemCount = this.intWarehouseAItemCount + 1;
//Calculate the total value of warehouse A.
this.dblTotalValueA = this.dblTotalValueA + intAddNumInStock * doubleAddValueOfOneItem;
//Create the warehouse A array list.
this.createWareHouseA();
//Put items into warehouse B if appropriate.
if (intAddNumInStock >= 25)
if (intAddNumInStock < 75)
//Increment the warehouse B item count.
this.intWarehouseBItemCount = this.intWarehouseBItemCount + 1;
//Calculate the total value of warehouse B.
this.dblTotalValueB = this.dblTotalValueB + intAddNumInStock * doubleAddValueOfOneItem;
//Create the warehouse B array list.
this.createWareHouseB();
//Put items into warehouse C if appropriate.
if (intAddNumInStock >= 75)
//Increment the warehouse C item count.
this.intWarehouseCItemCount = this.intWarehouseCItemCount + 1;
//Calculate the total value of warehouse C.
this.dblTotalValueC = this.dblTotalValueC + intAddNumInStock * doubleAddValueOfOneItem;
//Create the warehouse C array list.
this.createWareHouseC();
//display helpful information.
System.out.println("!--------------------------------");
System.out.println("!" + addItemName + " is the item name.");
System.out.println("!" + addNumInStock + " is the number in stock.");
System.out.println("!" + addInitWarehouse + " is the initial warehouse.");
System.out.println("!" + addValueOfOneItem + " is the value of one item.");
System.out.println("!--------------------------------------------------");
//Increment the counters.
count++;
/**Create and write to the output file. */
try
//Use the output file specified by the user.
PrintWriter out = new PrintWriter(outputFile);
/**Write warehouse A details.*/
//Blank the first line.
out.println(" ");
//Write the array list for warehouse A.
out.println(warehouseAList);
//Write the amount of items in warehouse A.
out.println(intWarehouseAItemCount);
//Write the total value for warehouse A.
out.println(dblTotalValueA);
/**Write warehosue B details.*/
//Write the array list for warehouse B.
out.println(warehouseBList);
//Write the amount of items in warehouse B.
out.println(intWarehouseBItemCount);
//Write the total value for warehouse B.
out.println(dblTotalValueB);
/**Write warehouse C details.*/
//Write the array list for warehouse C.
out.println(warehouseCList);
//Write the amount of items in warehouse C.
out.println(intWarehouseCItemCount);
//Write the total value for warehouse C.
out.println(dblTotalValueC);
//Close the output file.
out.close();
catch (FileNotFoundException e)
System.out.println("Error: Unable to open file for reading.");
catch (IOException e)
System.out.println("Error: Cannot read from file.");
/**View the contents and the value of each warehouse.*/
System.out.println("!---------------Inventory Summary------------------");
System.out.println("!--------------------------------------------------");
System.out.println("!--------------------LEGEND:-----------------------");
System.out.println("!<item type>, <amount in stock>,<value of one item>");
System.out.println("!--------------------------------------------------");
System.out.println("!------------------Warehouse A:--------------------");
System.out.println("!--------------------------------------------------");
//Display Items in warehouse A.
System.out.println(warehouseAList);
//Total items in warehouse A.
System.out.println("Total items: " + intWarehouseAItemCount);
//Display total value of warehouse A.
System.out.println("Total value: " + "$" + dblTotalValueA);
System.out.println("!--------------------------------------------------");
System.out.println("!------------------Warehouse B:--------------------");
System.out.println("!--------------------------------------------------");
//Display Items in warehouse B.
System.out.println(warehouseBList);
//Total items in warehouse B.
System.out.println("Total items: " + intWarehouseBItemCount);
//Display total value of warehouse B.
System.out.println("Total value: " + "$" + dblTotalValueB);
System.out.println("!--------------------------------------------------");
System.out.println("!------------------Warehouse C:--------------------");
System.out.println("!--------------------------------------------------");
//Display Items in warehouse C.
System.out.println(warehouseCList);
//Total items in warehouse C.
System.out.println("Total items: " + intWarehouseCItemCount);
//Display total value of warehouse C.
System.out.println("Total value: " + "$" + dblTotalValueC);
/**Display a help message.*/
private void displayHelp()
System.out.println("!--------------------------------");
System.out.println("! General Help:");
System.out.println("!--------------------------------");
System.out.println("! ");
System.out.println("!'help' display this help message.");
System.out.println("!'Q!' quit this program.");
System.out.println("!--------------------------------");
System.out.println("! Input File Specific Commands:");
System.out.println("!--------------------------------");
System.out.println("! ");
System.out.println("!'F' <name> type F followed by the name of the " +
"file to be used for input.");
System.out.println("!---------------------------------------");
System.out.println("! Input From Keyboard Specific Commands:");
System.out.println("!---------------------------------------");
System.out.println("! ");
System.out.println("!'K' <number> type K followed by the number of " +
"items that will be added. ");
System.out.println("! ");
}Program file:
public class InventoryProg
public static void main(String[] args)
//Create a new Inventory object.
Inventory test = new Inventory();
//Execute the command interpreter.
test.cmdInterpreter();
}Right now I am stuck on this and I cannot progress any further until I figure out how to input the data in the text file back into a arraylist.
Thanks in advance.Thanks but I figured it out. Heres a sample of the code i used to solve my problem:
try
//Warehouse A BufferedReader.
BufferedReader inA = new BufferedReader(new FileReader(inputFileWarehouseA));
//Warehouse B BufferedReader.
BufferedReader inB = new BufferedReader(new FileReader(inputFileWarehouseB));
//Warehouse C BufferedReader.
BufferedReader inC = new BufferedReader(new FileReader(inputFileWarehouseC));
//Warehouse details BufferedReader.
BufferedReader inDetails = new BufferedReader(new FileReader(inputFileDetails));
//Will hold values in warehouse arraylists.
String lineA = null;
String lineB = null;
String lineC = null;
//Will hold the details of each warehouse.
String line1 = null;
String line2 = null;
String line3 = null;
String line4 = null;
String line5 = null;
String line6 = null;
//Get the item count and total value for each warehouse.
while(inDetails.readLine() != null)
line1 = inDetails.readLine();
line2 = inDetails.readLine();
line3 = inDetails.readLine();
line4 = inDetails.readLine();
line5 = inDetails.readLine();
line6 = inDetails.readLine();
/**Assign the item count and total value to warehouse A.*/
//Cast.
int intLine1 = Integer.valueOf(line1).intValue();
double dblLine2 = Double.valueOf(line2).doubleValue();
//Assign the values.
this.intWarehouseAItemCount = intLine1;
this.dblTotalValueA = dblLine2;
/**Assign the item count and total value to warehouse B.*/
//Cast.
int intLine3 = Integer.valueOf(line3).intValue();
double dblLine4 = Double.valueOf(line4).doubleValue();
//Assign the values.
this.intWarehouseBItemCount = intLine3;
this.dblTotalValueB = dblLine4;
/**Assign the item count and total value to warehouse C.*/
//Cast.
int intLine5 = Integer.valueOf(line5).intValue();
double dblLine6 = Double.valueOf(line6).doubleValue();
//Assign the values.
this.intWarehouseCItemCount = intLine5;
this.dblTotalValueC = dblLine6;
/**Put the items back into the warehouses arraylists. */
//Add items to warehouse A.
while((lineA = inA.readLine()) != null)
warehouseAList.add(lineA);
//Add items to warehouse B.
while((lineB = inB.readLine()) != null)
warehouseBList.add(lineB);
//Add items to warehouse C.
while((lineC = inC.readLine()) != null)
warehouseCList.add(lineC);
}(this isn't the whole try statement its pretty long) -
How can I use Automator to extract specific Data from a text file?
I have several hundred text files that contain a bunch of information. I only need six values from each file and ideally I need them as columns in an excel file.
How can I use Automator to extract specific Data from the text files and either create a new text file or excel file with the info? I have looked all over but can't find a solution. If anyone could please help I would be eternally grateful!!! If there is another, better solution than automator, please let me know!
Example of File Contents:
Link Time =
DD/MMM/YYYY
Random
Text
161 179
bytes of CODE memory (+ 68 range fill )
16 789
bytes of DATA memory (+ 59 absolute )
1 875
bytes of XDATA memory (+ 1 855 absolute )
90 783
bytes of FARCODE memory
What I would like to have as a final file:
EXCEL COLUMN1
Column 2
Column3
Column4
Column5
Column6
MM/DD/YYYY
filename1
161179
16789
1875
90783
MM/DD/YYYY
filename2
xxxxxx
xxxxx
xxxx
xxxxx
MM/DD/YYYY
filename3
xxxxxx
xxxxx
xxxx
xxxxx
Is this possible? I can't imagine having to go through each and every file one by one. Please help!!!Hello
You may try the following AppleScript script. It will ask you to choose a root folder where to start searching for *.map files and then create a CSV file named "out.csv" on desktop which you may import to Excel.
set f to (choose folder with prompt "Choose the root folder to start searching")'s POSIX path
if f ends with "/" then set f to f's text 1 thru -2
do shell script "/usr/bin/perl -CSDA -w <<'EOF' - " & f's quoted form & " > ~/Desktop/out.csv
use strict;
use open IN => ':crlf';
chdir $ARGV[0] or die qq($!);
local $/ = qq(\\0);
my @ff = map {chomp; $_} qx(find . -type f -iname '*.map' -print0);
local $/ = qq(\\n);
# CSV spec
# - record separator is CRLF
# - field separator is comma
# - every field is quoted
# - text encoding is UTF-8
local $\\ = qq(\\015\\012); # CRLF
local $, = qq(,); # COMMA
# print column header row
my @dd = ('column 1', 'column 2', 'column 3', 'column 4', 'column 5', 'column 6');
print map { s/\"/\"\"/og; qq(\").$_.qq(\"); } @dd;
# print data row per each file
while (@ff) {
my $f = shift @ff; # file path
if ( ! open(IN, '<', $f) ) {
warn qq(Failed to open $f: $!);
next;
$f =~ s%^.*/%%og; # file name
@dd = ('', $f, '', '', '', '');
while (<IN>) {
chomp;
$dd[0] = \"$2/$1/$3\" if m%Link Time\\s+=\\s+([0-9]{2})/([0-9]{2})/([0-9]{4})%o;
($dd[2] = $1) =~ s/ //g if m/([0-9 ]+)\\s+bytes of CODE\\s/o;
($dd[3] = $1) =~ s/ //g if m/([0-9 ]+)\\s+bytes of DATA\\s/o;
($dd[4] = $1) =~ s/ //g if m/([0-9 ]+)\\s+bytes of XDATA\\s/o;
($dd[5] = $1) =~ s/ //g if m/([0-9 ]+)\\s+bytes of FARCODE\\s/o;
last unless grep { /^$/ } @dd;
close IN;
print map { s/\"/\"\"/og; qq(\").$_.qq(\"); } @dd;
EOF
Hope this may help,
H -
Populating a form from a text file
I have an Oracle form which schedules students into courses. The form collects the student id, name, school, and course code. A "RUN" button then does the scheduling. The form is not a table, meaning the data is not all stored together in an Oracle table. The user currently has to manually enter each piece of information before a student can be scheduled. I would like to be able to auto populate this form/screen with data from a text file. I cannot use SQL Loader since the data is not going into a table. Is there a way to take my text file and make it appear on the form/screen when the form opens? Then my user just has to click the RUN button in order to schedule the students instead of hand entering all the data.
Any help on this would be greatly appreciated!
-NTWhi
USING THE TEXT_IO PACKAGE
Abstract: This document describes the functionality of the TEXT_IO
package and explains how to use it to access the file
system effectively.
Keywords: TEXT_IO;FILE;IO;PACKAGE
Using the TEXT_IO Package
=========================
Oracle Procedure Builder, "an integrated, interactive environment for
PL/SQL", is shipped with several built-in packages which, if used
properly, can greatly boost development productivity. These built-in
packages are not installed as extensions to the STANDARD package;
hence, when you reference a construct from any of these packages, you
must prefix the package name to the construct.
TEXT_IO provides constructs that allow programmers to read information
from and write information to a file system. The procedures and
functions in TEXT_IO fall into the following three categories:
Category 1: File Operations
FILE_TYPE - Declares a file type variable as a handle to the file being
processed.
Syntax: TEXT_IO.FILE_TYPE;
FOPEN - Opens a file and returns a handle to the specified file of
type FILE_TYPE.
Syntax: TEXT_IO.FOPEN(file_specs VARCHAR2, file_mode VARCHAR2);
The file mode can be R(read), W(write) or A(append).
FCLOSE - Closes an open file.
Syntax: TEXT_IO.FCLOSE(file_specs VARCHAR2);
IS_OPEN - Checks if the specified file is currently open and returns a
boolean.
Syntax: TEXT_IO.IS_OPEN(file_type FILE_TYPE);
Category 2: Output Operations
PUT - Concatenates the supplied data to the current line of an open file.
Syntax: TEXT_IO.PUT(file FILE_TYPE, data DATA_TYPE)
Valid data types are VARCHAR2, DATE, NUMBER, PLS_INTEGER.
All data except VARCHAR2 is converted to a character string.
PUTF - Formats and writes a character string to an open file,
doing a C-like substitution.
Syntax: TEXT_IO.PUTF(file FILE_TYPE, format VARCHAR2,
arg1[,...,arg5] VARCHAR2);
Format is an optional parameter. If it is omitted, only
one argument value can be passed.
You can embed up to 5 "%s" patterns within the format string,
which can be replaced by the corresponding strings
(arg1 ... arg5) at execution.
PUT_LINE - Concatenates the given argument string to the file
followed by a newline character.
Syntax: TEXT_IO.PUT_LINE(file FILE_TYPE, data VARCHAR2);
NEW_LINE - Concatenates n number of newline characters to the current line,
where n is the second argument with a default value of 1.
Syntax: TEXT_IO.NEW_LINE(file FILE_TYPE, n PLS_INTEGER := 1);
Note: If the file name is not specified each of the above cases, the
output is directed to the Interpreter.
Category 3: Input Given Operations
GET_LINE - Reads a line from an open file into the parameter.
Syntax: TEXT_IO.GET_LINE(file FILE_TYPE, data_item OUT VARCHAR2);
Note: After a GET_LINE call, the file pointer moves to the next
line and subsequent lines are read in after each call. If the
line to be read exceeds the size of data_item, the VALUE_ERROR
exception is raised. If no more characters can be read from the
file, the NO_DATA_FOUND exception is raised. You cannot move this
pointer back to the previous line though this can be simulated
using your own buffer scheme.
If a file name is provided for any of the above routines, this file
must be accessible to Oracle Forms. In addition, you must provide the
complete path. If no path is given, Forms assumes the file is in the
current working directory and does not search for the file in the file
system. The accessibility is determined as follows:
On Windows, a TEXT_IO package function call only accesses local
drives. It does not recognize any Universal Naming Conventions like
\\machine_name\drive_letter. To access files on remote machines using
the TEXT_IO package, map a letter to the remote drive through the File
Manager.
On UNIX, the absolute path must be given for the location of the file.
Forms does not recognize relative paths provided for the file. This is also
the case for VMS and other platforms. When you do not specify a path, Forms
assumes the file is in the current working directory.
For more information, refer to the TEXT_IO Package section in the
"Oracle Procedure Builder Packages" chapter of the Oracle
Developer/2000 Procedure Builder Developer's Guide Manual.
Sample Form
The following sample form explains some of the concepts and the
syntax. The form reads in lines from a specified text file one at a
time and displays them in a text item. It enables the user to parse
the file by getting the next or the previous line. In addition, the
user can write any line currently displayed to a specified output
file.
Create a single non-base table block. Put the following items and
buttons on it. Create the appropriate boilerplate text for each item.
All items go on the same canvas. No database connection is required
for this application.
Create the following text items:
1. Name INPUT_FILE_SPECS
Item Type Text Item
Data Type Char
Maximum Length 30
2. Name LINE_READ
Item Type Text Item
Data Type Char
Maximum Length 300
3. Name OUTPUT_FILE_SPECS
Item Type Text Item
Data Type Char
Maximum Length 30
4. Name LINE_NO
Item Type Text Item
Data Type Number
Maximum Length 30
Create the following buttons and associated triggers:
1. Name OPEN_AND_READ_FROM_FILE
Label Echo file using TEXT_IO package
Associated Button Trigger:
Name WHEN-BUTTON-PRESSED
Trigger Text:
IF :input_file_specs IS NOT NULL THEN
:line_no := 1;
ECHO_TEXT_IO;
ELSE
MESSAGE('You must enter a valid input file name
with a complete path');
END IF;
2. Name NEXT
Label NEXT LINE
Associated Button Trigger:
Name WHEN-BUTTON-PRESSED
Trigger Text:
:line_no := :line_no + 1;
ECHO_TEXT_IO;
3. Name PREVIOUS
Label PREVIOUS LINE
Associated Button Trigger:
Name WHEN-BUTTON-PRESSED
Trigger Text:
IF :line_no = 1 THEN
MESSAGE('You are on the first line of the file.');
ELSE
:line_no := :line_no - 1;
TEXT_IO.FCLOSE(variable_declarations.infile);
/* Close the file then reopen it with the
ECHO_TEXT_IO package. This resets the
file pointer. */
ECHO_TEXT_IO;
END IF;
4. Name WRITE_LINE_TO_FILE
Label WRITE CURRENT LINE TO Output FILE
Associated button trigger:
Name WHEN-BUTTON-PRESSED
Trigger Text:
IF :output_file_specs IS NOT NULL THEN
write_to_file;
ELSE
MESSAGE('Must enter a valid output file name with
complete path');
END IF;
Create the following program units and package specifications:
1. ECHO_TEXT_IO* (Procedure Body)
PROCEDURE echo_text_io IS
-- infile TEXT_IO.FILE_TYPE; /* Not used in this program */
linebuf VARCHAR2(300);
line_counter INTEGER;
BEGIN
line_counter := 0;
Note that the IF condition would be redundant if you use
a local variable (commented out above) to save the file pointer.
Infile is a local variable, so the binding would be lost each
time you exited the program. The use of package variables
to act as global file type handles resolves this problem.
IF TEXT_IO.IS_OPEN(variable_declarations.infile) THEN
If the file is open, read in the next line.
TEXT_IO.GET_LINE(variable_declarations.infile, linebuf);
line_counter := line_counter + 1;
ELSE
The file is closed for the application when you display the
previous line; see the WHEN_BUTTON_PRESSED trigger on the
PREVIOUS item. Since the file pointer cannot move
backwards, you must reset the file pointer and loop to the
specified line.
variable_declarations.infile := TEXT_IO.FOPEN(:INPUT_FILE_SPECS, 'r')
-- variable_declarations.infile := TEXT_IO.FOPEN('c:\autoexec.bat', 'r')
/* You can also hard-code the value */
WHILE line_counter < :line_no LOOP
TEXT_IO.GET_LINE(variable_declarations.infile, linebuf);
line_counter := line_counter + 1;
END LOOP;
END IF;
:line_read := linebuf;
EXCEPTION
WHEN NO_DATA_FOUND THEN
MESSAGE('End Of File reached.');
:line_no := :line_no - 1;
WHEN OTHERS THEN
MESSAGE('UNHANDLED EXCEPTION RAISED in ECHO_TEXT_IO
procedure - Check the file name');
MESSAGE('U. E. R.');
END;
2. VARIABLE_DECLARATIONS (Package Spec)
PACKAGE variable_declarations IS
The following declarations are public and, hence, visible
to the Forms application.
infile TEXT_IO.FILE_TYPE;
outfile TEXT_IO.FILE_TYPE;
line_number NUMBER;
END;
3. WRITE_TO_FILE* (Procedure Body)
PROCEDURE write_to_file IS
BEGIN
IF NOT TEXT_IO.IS_OPEN(variable_declarations.outfile) THEN
variable_declarations.outfile := TEXT_IO.FOPEN(:OUTPUT_FILE_SPECS, 'a');
END IF;
TEXT_IO.PUT_LINE(variable_declarations.outfile, :line_read);
END;Sarah -
Retrieving certain line from a text file
Hi,
I would like to know on how to read a specific line from a text file using NetBeans IDE 6.1? Below is the content of my text file and my code.I will appreciate if anyone can help. Thank in advance= D
Matrix1.text
<matrix>
rows = 2
cols = 2
1 2
2 4
</matrix>
I would like to retrieve the interger 1,2,2,4.
MyCode.java
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
class Matrix {
double [][] element;
static void getFile(String fileName) throws IOException{
int counter = 0;
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null){
line = br.readLine();
System.out.println(line);
counter ++;
System.out.println("Total line : " + counter);
br.close();
}catch(FileNotFoundException ex){
System.out.println(ex.getMessage());
}Wonders wrote:
Thank for reply=D
Yap the row and column will change but i had already parse these lines into my code. However, i am still figuring on how to get the integer number 1,2,2,4 of the text file using while loop and not include the "</matrix>" in the reading. Can this be done?If the numbers you want are at fixed byte positions in the file that are known ahead of time, you can use java.io.RandomAccessFile to skip to those positions. However, that seems unlikely.
If, as is the more likely case, those are not at fixed positions, you'll have to read everything preceding them. (Note that this is not a Java issue. This is how file I/O works.) You'll need to ignore the lines that are meaningless to you (read those lines and do nothing with them) figure out, by whatever rules you have--line numbers, preceding tokens, whatever--when you're at the lines you do care about, and then read and process those lines accordingly. -
How do you read data from a text file into a JTextArea?
I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?
Student_Coder wrote:
1) Read the file messages.txt into a String
2) Initialize messages with the String as the textSwing text components are designed to use Unix-style linefeeds (\n) as line separators. If the text file happens to use a different style, like DOS's carriage-return+linefeed (\r\n), it needs to be converted. The read() method does that, and it saves the info about the line separator style in the Document so the write() method can re-convert it.
lethalwire wrote:
They have 2 different ways of importing documents in this link:
http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
Neither of those methods applies to JTextAreas. -
How to save input from a text file in to array
I got this assignment, and almost have no clue, and my teacher doesn't even teaches us anything
This is what i am suppose to do
5. The program must store the following data about each student in this Talent Show:
* The student's name (store as a String)
* The student's average time score [only for the events they competed in] (store as a Double)
Note: Some of the data comes directly from the text file, and some of the data must be calculated from the data that is read from the file.
6. The program must search through all of the student's scores to find the student who has the minumum average time of all students.
7. You must calculate how many events each student played. Zero values are not counted.
8. You must then generate a report on the screen that prints out
* the total number of students in the competition,
* the winning student's ...
o name
o times
o average time (rounded to one decimal places)
Sample output
btw this is the data file
Bart Simpson
7.5
12.3
7.8
19.2
9.9
5.3
8.5
11.8
2.2
4.6
Stewie Griffin
9.5
29.7
7.8
22.5
9.9
12.6
8.5
0
8.2
0
Pinky
2.5
0
1.8
0
3.9
0
6.5
0
5.2
12.1
Rocky N Bullwinkle
10.0
22.2
9.5
17.5
9.9
1.5
8.7
23.7
9.2
11.0
Angelica Pickles
5.5
11.1
6.8
12.2
7.9
13.3
8.1
5.1
7.2
7.9
Pink Panther
8.5
5.5
8.8
6.6
8.9
7.7
9.9
8.8
2.2
9.9
Josie
9.5
0
8.8
12.2
9.9
0
8.5
0
9.2
5.3
Rogue
8.5
1.1
7.8
2.2
7.9
3.3
7.5
4.4
8.2
5.5
Usagi Tsukino
8.5
15.5
8.8
30.1
9.9
19.7
9.5
11.0
8.2
8.6
Yosemite Sam
0
15.2
0
29.5
3.9
0
0
16.0
0
7.7
My code so far
import java.io.*;
public class test
public static void main (String [] args)
FileInputStream File1;
DataInputStream In;
String fileInput = "";
try
File1 = new FileInputStream ("data.txt");
In = new DataInputStream (File1);
while (In.available () > 0)
fileInput = In.readLine ();
System.out.println (fileInput);
In.close ();
catch (FileNotFoundException e)
System.out.println ("Error - this file does not exist");
catch (IOException e)
System.out.println ("error=" + e.toString ());
}My question, how do i save the data in to an array, and how do i seperatly save names in to different array, and their scores in to different arrays
bte he said you can use scanner class
Thanks
Edited by: supahsain08 on Mar 26, 2008 2:55 PMsupahsain08 wrote:
Well, you are not in my class and you don't even know my teacher
who are you to judge meHe is jaded by our experiences here. 99% of posters who complain that the teacher doesn't teach have adequate (note that I didn't say good) teachers, but it's the student who is failing to take responsibility for his own education. It is after all your responsibility and complaining won't help you any.
Good luck. -
How can i delete a UserName from a text file using Strings or io.
hi i m trainee
i have been assigned to make java program which deletes a UserName and
his Passwor from a Text File
i m unable to do it using the code below
plz help
do reply
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java .applet.*;
import java.io.*;
class Del extends JFrame implements ActionListener
String s2;
JTextField CWDMUserDText = new JTextField();
JButton CWDMSecDelButton = new JButton("DELETE");
JLabel CWDMUserLabel = new JLabel("USER NAME");
JPasswordField CWDMPassDText = new JPasswordField();
JLabel CWDMPassLabel = new JLabel("PASSWORD");
//String user,pass;
/* CONSTRUCTOR*/
Del()
Container contentPane=getContentPane();
contentPane.setLayout(null);
setLocation(400,200);
contentPane.add(CWDMUserDText);
contentPane.add(CWDMSecDelButton);
contentPane.add(CWDMUserLabel);
contentPane.add(CWDMPassDText);
contentPane.add(CWDMPassLabel);
CWDMUserLabel.setBounds(20,70,100,25);
CWDMPassLabel.setBounds(20,100,100,25);
CWDMUserDText.setBounds(150,70,100,25);
CWDMPassDText.setBounds(150,100,100,25);
CWDMSecDelButton.setBounds(80,135,100,25);
CWDMUserDText.addActionListener(this);
CWDMPassDText.addActionListener(this);
CWDMSecDelButton.addActionListener(this);
contentPane.setBackground(Color.CYAN);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public void actionPerformed(ActionEvent ae)
if(ae.getSource()==CWDMSecDelButton)
// user = CWDMUserDText.getText();
// pass = CWDMPassDText.getText();
// showarr();
s2 = CWDMUserDText.getText();
CWDMUserDText.setText("");
CWDMPassDText.setText("");
DelUser(s2);
public static void main(String args[])
Del myframe1= new Del();
myframe1.setSize(300,200);
myframe1.setVisible(true);
public void DelUser(String s)
//int a;
try
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String s1;
int a;
int len = s.length();
System.out.println(len);
//s2 = CWDMUserDText.getText();
while ((s1=br.readLine()) !=null)
if((a=s1.indexOf(s))>0 && (a=s1.indexOf(s))!=0)
System.out.println(a);
fr.close();
catch(FileNotFoundException e)
System.out.println("exception occured");
catch(IOException e)
System.out.println("io");
}Some tips:
1) If you are adding or deleting stuff from a text file you need to write a new, modified file and then, optionally, do something like:
rename the old file to whatever.bak or the like.
rename the new file to the old.
2) Don't depend on System.out so much on a GUI application. For example if you get an exception use javax.swing.JOptionPane to display an alert (and show the message from the exception). You can write the stack trace to System.out if you want.
3) Don't muck about with calculating bounds for screen objects, let a layout manager sort it out. I like BoxLayoutManager for most things like this.
4) For bonus points do your IO in a separate Thread. Generally you don't want anything happening in an actionPerformed method which significantly delays it's return. The method should launch a new Thread to do the job, and disable the button until the Thread finishes. -
hey ppl
i have a datagrid in my form.i need to read input(fields..sort of a database) from a text file and display its contents in the datagrid.
how can this be done.. and also after every few seconds reading event should be re executed.. and that the contents of the datagrid will keep changing as per the changes in the file...
please help as this is urgent and important.. if possible please provide me with an example code as i am completely new to flex...
thanks.....It's not possible to read from a file without using classes from the core API*. You'll have to get clarification from your instructor as to which classes are and are not allowed.
[http://java.sun.com/docs/books/tutorial/essential/io/]
*Unless you write a bunch of JNI code to replicate what the java.io classes are doing. -
Error while loading data from a text file to a datastore
Hi all,
i am a starter in ODI. I am trying to load data from a text file into a datastore. I have put the file on a unix server whose location is defined in the topology manager. when i am trying to "view data" it is giving me error file does not exist at <location where i have put the file>. Please help meHi,
1. If your files are on a remote File System, you will need to copy one of your files to the machine ODI Designer is running on to allow ODI to retrieve the metadata information of the file.
2. In Topology create a Physical Schema, the directory you enter for Data and Work Schema should point at this local file.
3. Then define the File Datastore in ODI Designer. Enter a name, browse and select the file and fill in each filed of the Files tab.
* If its a Fixed file, click on the grid icon on the Columns tab to enter the columns and have Automatic Adjustment checked.
* If its a Delimited file, use the Reverse button on the Columns tab to reverse the columns.
* Right click on the File Datastore select View Data, if you can view data, that means the File Datastore has been defined correctly.
* If not, check each tab of the File Datastore to make sure everything is defined correctly and retry.
4. Once View Data is successful, you now change the directories (Data and Work Schema in Topology) to point at the remote File System. These directories must be accessible to the ODI Agent that will be used to run the transformations. The directory can be an absolute path (m:/public/data/files) or relative to the ODI Agent startup directory (../demo/files). It is strongly advised to use a UNC (independent from the execution location) for the path. When running the transformations with "no agent", the directory is relative to the directory where Oracle Data Integrator has been installed.
You need to have a agent process running at the system where your source file resides .
Then while running the odi interface choose that agent .
Thanks,
Sutirtha -
Getting repeated values when reading from a text file.
I need to read from a text file. When the token encounters a particular word (command) I need to read the next line and perform some actions. However, this part is working but it is repeating the values again and again until it encounters the next particular word (command). Hope that someone will help me out, as always when I posted a problem in these forums.
SetOperations class - contains the set methods
// Imported packages.========================================================
import java.util.Vector;
import java.util.Iterator;
// Public class SetOperations.===============================================
public class SetOperations
// Instance variables.===================================================
private Vector v = null; // Creates new instance of vector.
protected int memberCount;
// Constructor.==========================================================
public SetOperations()
v = new Vector();
} // end constructor.
// Method isMember.======================================================
* Checks whether the element is already a member of the set.
* @return True if Vector v contains Object member.
public boolean isMember(Object member)
if (member != null) // only if Object member is not null.
return v.contains(member); // returns true if vector already contains member.
else
return false; // returns false if vector does not contain member.
} // end public boolean isMember(Object member).
// Method addMember.=====================================================
* Adds a member to the set.
* @return Adds Object member to Vector v.
public void addMember(Object member)
//if (! v.contains(member)) // only if element is not already a member.
if (isMember(member) == false) // only if element is not already a member.
v.add(member); // adds a member.
} // end public void addMember(Object member).
// Method countMember.===================================================
* Returns the number of members present in the vector.
* @return Number of elements present in the vector.
public int countMember()
return v.size();
} // end public int countMember().
// Method isSetEmpty.====================================================
* Returns true if set is empty.
* @return True if no elements are present in Vector v.
public boolean isSetEmpty()
return v.size() == 0; // returns 0 if no elements are present in the vector.
} // end of public boolean isSetEmpty().
// Method printMember.===================================================
* Displays member/s of the set.
* @return Prints element/s present in the vector.
public void printMember()
for (int i = 0; i < v.size(); i++) // iterates through present members.
System.out.println("[" + i + "] " + v.get(i)); // displays member/s present in the vector.
} // end of public void printMember().
} // end public class SetOperations.
SetTextLauncher class - reads from a text file and implements the set operations
// Imported packages.========================================================
import java.util.*;
import java.io.*;
// Public class SetTestLauncher.=============================================
public class SetTestLauncher
// Main method public static void main(String args[]).===================
public static void main(String args[])
displayFile("test.txt"); // outputs result from text file.
// method to display a file on screen
public static void displayFile (String textFile)
// Instance variables.===============================================
// Creates new instances of SetOperations.
SetOperations setA = new SetOperations();
SetOperations setB = new SetOperations();
SetOperations setC = new SetOperations();
SetOperations setD = new SetOperations();
SetOperations setE = new SetOperations();
// Initialisation.
String line = "", nextLine = "";
FileReader fr = null;
try
// Opens the file with the FileReader data sink stream.
fr = new FileReader(textFile);
// Converts the FileReader input stream with the BufferedReader processing stream.
BufferedReader br = new BufferedReader(fr);
// Iterates through text file reading lines until end of text lines.
while (line != null)
line = br.readLine(); // reads one line at a time.
if(line == null) break; // when the line is null break the loop.
// Creates a new instace of StringTokenizer.
StringTokenizer st = new StringTokenizer(line);
// Loops until there are no more tokens.
while (st.hasMoreTokens())
String token = st.nextToken(); // reads next token.
// Only if the token encounters the String "membera".
if(token.equals("membera"))
nextLine = br.readLine(); // gets next line.
setA.addMember(nextLine); // adds a member to the set.
// Displays members present in the set if vector is not empty.
if (! setA.isSetEmpty())
setA.printMember(); // print members present.
// Displays the number of member/s present in the vector.
System.out.println("Number of set members: " + setA.countMember());
// Catches and displays exceptions.
catch (FileNotFoundException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
catch (IOException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
finally
try
// if file is found
if (fr != null)
// close file
fr.close();
catch (IOException exp)
exp.printStackTrace();
} // end public static void main(String args[]).
} // end public class SetTestLauncher.Thanks for your interest. Please ignore SetOperations class, it is just the class containing the methods and it works correctly since I checked it without reading from a text file. I marked the part where I think lies my problem in class SetTestOperations.
The information in the text file is as follows:
membera
Hillman
membera
Skoda
membera
Honda
membera
Toyota
and the result is:
[0] Hillman
Number of set members: 1
[0] Hillman
[1] Skoda
Number of set members: 2
[0] Hillman
[1] Skoda
[2] Honda
Number of set members: 3
[0] Hillman
[1] Skoda
[2] Honda
[3] Toyota
Number of set members: 4
instead of just one set:
[0] Hillman
[1] Skoda
[2] Honda
[3] Toyota
Number of set members: 4
Hope it is easier to understand like this.
Regards
Marco
I need to read from a text file. When the token
encounters a particular word (command) I need to read
the next line and perform some actions. However, this
part is working but it is repeating the values again
and again until it encounters the next particular
word (command). Hope that someone will help me out,
as always when I posted a problem in these forums.
SetOperations class - contains the set
methods
// Imported
packages.=============================================
===========
import java.util.Vector;
import java.util.Iterator;
// Public class
SetOperations.========================================
=======
public class SetOperations
// Instance
e
variables.============================================
=======
private Vector v = null; // Creates new instance of
f vector.
protected int memberCount;
Constructor.==========================================
================
public SetOperations()
v = new Vector();
} // end constructor.
// Method
d
isMember.=============================================
=========
* Checks whether the element is already a member of
f the set.
* @return True if Vector v contains Object member.
public boolean isMember(Object member)
if (member != null) // only if Object member is not
ot null.
return v.contains(member); // returns true if
if vector already contains member.
else
return false; // returns false if vector does not
not contain member.
} // end public boolean isMember(Object member).
// Method
d
addMember.============================================
=========
* Adds a member to the set.
* @return Adds Object member to Vector v.
public void addMember(Object member)
//if (! v.contains(member)) // only if element is
is not already a member.
if (isMember(member) == false) // only if element
nt is not already a member.
v.add(member); // adds a member.
} // end public void addMember(Object member).
// Method
d
countMember.==========================================
=========
* Returns the number of members present in the
e vector.
* @return Number of elements present in the vector.
public int countMember()
return v.size();
} // end public int countMember().
// Method
d
isSetEmpty.===========================================
=========
* Returns true if set is empty.
* @return True if no elements are present in Vector
r v.
public boolean isSetEmpty()
return v.size() == 0; // returns 0 if no elements
ts are present in the vector.
} // end of public boolean isSetEmpty().
// Method
d
printMember.==========================================
=========
* Displays member/s of the set.
* @return Prints element/s present in the vector.
public void printMember()
for (int i = 0; i < v.size(); i++) // iterates
es through present members.
System.out.println("[" + i + "] " + v.get(i)); //
// displays member/s present in the vector.
} // end of public void printMember().
} // end public class SetOperations.
SetTextLauncher class - reads from a text file
and implements the set operations
// Imported
packages.=============================================
===========
import java.util.*;
import java.io.*;
// Public class
SetTestLauncher.======================================
=======
public class SetTestLauncher
// Main method public static void main(String
g args[]).===================
public static void main(String args[])
displayFile("test.txt"); // outputs result from
om text file.
// method to display a file on screen
public static void displayFile (String textFile)
// Instance
ce
variables.============================================
===
// Creates new instances of SetOperations.
SetOperations setA = new SetOperations();
// Initialisation.
String line = "", nextLine = "";
FileReader fr = null;
try
// Opens the file with the FileReader data sink
ink stream.
fr = new FileReader(textFile);
// Converts the FileReader input stream with the
the BufferedReader processing stream.
BufferedReader br = new BufferedReader(fr);
// Iterates through text file reading lines until
til end of text lines.
while (line != null)
line = br.readLine(); // reads one line at a
at a time.
if(line == null) break; // when the line is null
null break the loop.
// Creates a new instace of StringTokenizer.
StringTokenizer st = new StringTokenizer(line);
// Loops until there are no more tokens.
while (st.hasMoreTokens())
String token = st.nextToken(); // reads next
next token.
// Only if the token encounters the String
tring "membera".
if(token.equals("membera"))
// *****THE PROBLEM LIES HERE....I GUESS
// need to read the next line after encountering the word membera in text file
nextLine = br.readLine(); // gets next line.
setA.addMember(nextLine); // adds a member to
ber to the set.
// Displays members present in the set if
set if vector is not empty.
if (! setA.isSetEmpty())
setA.printMember(); // print members present.
// Displays the number of member/s present in
ent in the vector.
System.out.println("Number of set members: " +
s: " + setA.countMember());
// Catches and displays exceptions.
catch (FileNotFoundException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
catch (IOException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
finally
try
// if file is found
if (fr != null)
// close file
fr.close();
catch (IOException exp)
exp.printStackTrace();
} // end public static void main(String args[]).
} // end public class SetTestLauncher. -
At end of tether! Reading in variables from a text file
Hi all
My stress factor has gone through the roof because I am trying to read in from a text file (you may have seen some earlir questions about ArrayLists) it's just not working!
The code is below. The result is that it's reading in all of the car data, none of the motorbike and only the first line for the services. It's odd and it's driving me insane!
Here's an example of the data it's reading. There are about 7-10 sets of data per type
<car><reg>AB04CDE</reg><make>Ford</make><model>Fiesta</model><colour>blue</colour><passenger_no>4</passenger_no></car>
<service><service_no>13570</service_no><reg>J605PLE</reg><date>15:07:2006</date><miles>20000</miles><part_replaced>brake_pads</part_replaced><part_replaced>front_tyres</part_replaced></service>
<motorbike><reg>TT05EKJ</reg><make>Triumph</make><model>Speedmaster</model><colour>black</colour><load>20.50</load></motorbike>
Here's the code
while (moreToRead) {
String line;
try {
line = fileReader.getNextStructure();
// collect the data from the file
if (line.indexOf("<car>")> -1){
// Select/Extract the registration element
int nStart = line.indexOf("<reg>");
int nEnd = line.indexOf("</reg>");
String reg = line.substring(nStart+5,nEnd);
// Select/Extract the make element
nStart = line.indexOf("<make>");
nEnd = line.indexOf("</make>");
String make = line.substring(nStart+6,nEnd);
// Select/Extract the model element
nStart = line.indexOf("<model>");
nEnd = line.indexOf("</model>");
String model = line.substring(nStart+7,nEnd);
// Select/Extract the colour element
nStart = line.indexOf("<colour>");
nEnd = line.indexOf("</colour>");
String colour = line.substring(nStart+8,nEnd);
// Select/Extract the passenger_no element
nStart = line.indexOf("<passenger_no>");
nEnd = line.indexOf("</passenger_no>");
String passenger_no = line.substring(nStart+14,nEnd);
//convert string to int
int passengerInt = Integer.parseInt(passenger_no);
// declare new object car and assign the variables then add it to the array.
Car c = new Car (reg, make, model, colour, passengerInt);
carList.add(c);
} else if (line.indexOf("<bike>")> -1) {
// Select/Extract the registration element
int nStart = line.indexOf("<reg>");
int nEnd = line.indexOf("</reg>");
String reg = line.substring(nStart+5,nEnd);
// Select/Extract the make element
nStart = line.indexOf("<make>");
nEnd = line.indexOf("</make>");
String make = line.substring(nStart+6,nEnd);
// Select/Extract the model element
nStart = line.indexOf("<model>");
nEnd = line.indexOf("</model>");
String model = line.substring(nStart+7,nEnd);
// Select/Extract the colour element
nStart = line.indexOf("<colour>");
nEnd = line.indexOf("</colour>");
String colour = line.substring(nStart+8,nEnd);
// Select/Extract the load element
nStart = line.indexOf("<load>");
nEnd = line.indexOf("</load>");
String load = line.substring(nStart+6,nEnd);
//convert load string to double
double bikeLoad = Double.parseDouble(load);
// declare new object motorbike and assign the variables then add it to the array.
Motorbike m = new Motorbike (reg, make, model, colour, bikeLoad);
bikeList.add(m);
} else {
// Select/Extract the service_number element
int nStart = line.indexOf("<service_no>");
int nEnd = line.indexOf("</service_no>");
String service_no = line.substring(nStart+12,nEnd);
console.println("service = " + service_no);
nStart = line.indexOf("<reg>");
nEnd = line.indexOf("</reg>");
String reg = line.substring(nStart+5,nEnd);
console.println("service = " + reg);
nStart = line.indexOf("<date>");
nEnd = line.indexOf("</date>");
String date = line.substring(nStart+6,nEnd);
console.println("service = " + date);
nStart = line.indexOf("<miles>");
nEnd = line.indexOf("</miles>");
String miles = line.substring(nStart+7,nEnd);
console.println("service = " + miles);
nStart = line.indexOf("<part_replaced>");
nEnd = line.indexOf("</part_replaced>");
String part_replaced = line.substring(nStart+15,nEnd);
console.println("service = " + part_replaced);
//convert string to int
int dateOfService = Integer.parseInt(date);
//convert string to double
double milesAtService = Double.parseDouble(miles);
//convert service no to unique int
int serviceNo = Integer.parseInt(service_no);
// declare new object service and assign the variables then add it to the array.
Service s = new Service (reg, part_replaced, serviceNo, dateOfService, milesAtService);
serviceList.add(s);
catch (Exception e) {
// Run out of data
moreToRead = false;
} If anyone can spy anything that could be causing this I love your advice. I simply can't see it.
Johi jos,
we have been asked not to use a parser for this assignment. evil
tutor i think! lolYour example seems to imply that all the <tag> ... </tag> pairs have
to occur on a single line; if that is so, you can do some cheap
programming like this:String getText(String line, String tag) {
int start= line.indexOf("<"+tag+">");
int end= line.indexOf("</"+tag+">", start);
if (start < 0 || end < 0) return null; // no <tag> ... </tag> pair found
// return the text in between the <tag> ... </tag> tags
return line.substring(start+tag.length()+2, end);
}kind regards,
Jos
Maybe you are looking for
-
Dataguard switching back to primary from standby:
I have switched my Primary database to standby database successfully. I am now in the process of switching the standby back to the primary However I am running into a small problem. I am using the command alter system set log_archive_dest_2=defer; bu
-
File-Save As form in SharePoint
How can i get Adobe reader or Pro to do a file save as to the same location in SharePoint?
-
Is there a way to set my music as a ringtone?
I would like to set my music as ringtones. Is it possible? and how?
-
What should you use a second SSD for?
Hi I have a few SSD drives and want to maximise the speed my Mac boots up but also in the apps I use. One of the drives is a Scratch Disk I use for FCPX. Should I keep my iTunes Library, Apps, Mail and Photos on a separate SSD to my boot drive to ma
-
How to dynamically validate users at run time using connection pools ?
Hi Folks We are facing a peculiar situation . We have established connection to our oracle 8i database using Oracle Thin driver using conenction pooling at the weblogic server . We set up connection pools at the console to set up connections to thge