Problem in writing to a file

hi all ...
i am writing a simple html to a file in swing applicaiotn,the file is created but the content is not writing what may be the reason..can any one help me......
Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.sql.*;
import javax.swing.filechooser.*;
public class MyAppFrame extends JFrame implements ActionListener{
     //-- class members
     JTextField jtf_Text;
     JButton jb_Button,G_Button;
     JList j1_List;
     Vector v;
private JScrollPane jpane;
final JFileChooser fc = new JFileChooser();
MyAppFrame(String title) {
     super(title);
     setSize(600,500);
     Container contentPane = getContentPane();
     contentPane.setLayout(new BorderLayout());
          JPanel panel = new JPanel();
     panel.setLayout(new FlowLayout());
          panel.add(new JLabel("Target Folder: "));
panel.add(jtf_Text = new JTextField(10));
jb_Button=new JButton("List");
jb_Button.addActionListener(this);
panel.add(jb_Button);
G_Button=new JButton("Generate");
panel.add(G_Button);
G_Button.addActionListener(this);
contentPane.add(panel,BorderLayout.NORTH);
panel = new JPanel();
          panel.setLayout(new GridLayout(2,1));
          panel.add(new JLabel("Selected Forms:"));
v=new Vector();
panel.add(j1_List = new JList());
//j1_List.setEnabled(false);
jpane = new JScrollPane();
jpane.getViewport().add(j1_List);
contentPane.add(panel, BorderLayout.CENTER);
panel.add(jpane);
          addWindowListener(new ExitListener());
     setVisible(true);
     public static void main(String[] args) {
     MyAppFrame maf = new MyAppFrame("Form Selection");
class ExitListener extends WindowAdapter{
public void windowClosing(WindowEvent event) {
System.exit(0);
private void con(){
          Connection con=null;
     ResultSet rs=null;
     try{
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:satya");
     System.out.println("Set Connection");
     Statement st=con.createStatement();
     String query="select form_name from form";
     System.out.println(query);
rs=st.executeQuery(query);
while(rs.next()){
          String name = rs.getString("form_name");
          //JLabel l=new JLabel(name);
          //j1_List.add(l);
          v.add(name);
          // System.out.println(name);
               j1_List.setListData(v);
               catch(Exception e)
e.printStackTrace();
public void actionPerformed(ActionEvent e) {
String flag = e.getActionCommand();
if(flag.equals("List")){
this.con();
else
     StringBuffer sb = new StringBuffer();
     sb.append("<html><h1>Hai</h1></html>");
     String formname=(String)j1_List.getSelectedValue();
     String Dir=jtf_Text.getText();
     Dir +="\\0ne.txt";
     if(formname!=null && Dir !=null)
     try
     PrintWriter out= new PrintWriter(new FileWriter(Dir));
//BufferedWriter br=new BufferedWriter(out);
     out.println(sb);
catch(Exception e1)
System.out.println(e1);
     //jb_Button.setEnabled(false);
//jb_Button.addActionListener(this);
//StringBuffer Sb = new StringBuffer();

http://forum.java.sun.com/thread.jsp?forum=57&thread=299655

Similar Messages

  • Problem in writing to the file

    I use this labview code to read and save some electrical measurement data from a set of instruments. I am having a problem that the code stops writing to the file after a while. It stops responding too. The only way to stop it then is to use the task manager and kill it. The code was written for an older version of labview but now I am using labview 9. Everything else seems updated but there's a section that uses Write characters to file vi and that may be causing the problem. I made a few futile attempts to change it. I would highly appreciate if someone takes a look at it and could tell me what's going wrong.
    Attachments:
    JANUS 2.2_4K Probe edit (2).vi ‏60 KB

    I will second aeastet's advice - please look into how state machines and producer/consumer loops work and use them.  Your program is very inefficient, but is very similar to what I would have written before I learned about state machines and producer/consumer loops.  Start with the LabVIEW help and go from there.  These forums and the National Instruments website can give you lots of help.
    Two things that will help you for this particular problem:
    At every loop iteration, you are opening the file, seeking to the end of it, appending data, then closing the file.  This is very slow and the code you use, as mentioned above, will not work if the file size exceeds 2GBytes.  I would recommend you open the file once, then use the write primitive to write to it until you finish, then close it.  You do not need the write character to file VI.  No seeking.  No repetitive opening and closing.  You can either open and close outside the loop, or use case structures and boolean flags (as you have done for other things) to open and close inside the loop.
    After you write to the file, if you choose to graph, you are reopening the file, reading the entire thing, and plotting this data.  This is another major slowdown that will only get worse as your file gets bigger.  You would be far better off caching the data in a shift register and plotting it on demand.  It would probably take less memory, as well.  You may want to read the tutorial Managing Large Data Sets in LabVIEW.
    One last tip.  You use Value properties to read and set the values of front panel controls.  Local variables are far faster (about three orders of magnitude).  However, do not make the mistake of using local variables for data storage.  Data is wires.  Local variables are a way to communicate to the front panel.  You seem to have this down, but a reminder to others reading this thread is in order.
    Let us know if you need more explanation or help.  Good luck!
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Problem in writing to CSV file

    Hi all,
    i am retreiving a long String which is not in a proper format (ie) Lot of Spaces in between and my String contains comma(,) seperated and I am trying to put that string in to a CSV file. I am able to write the data in the CSV file but not in a proper format.i need to write the data in the below format.
    For Ex:
    Emp-No,Address,Name,Manager -------> this is Heading
    1000,abcd,name,Man-name -----> After i have to put the data in next line
    My String will be like this,
    abcd , , , jsjsj, , ,saalkj,jfjfjfjf,mmm, nnn, , ,
    I am able to get the data properly in the CSV format.
    Please help me to solve this. Thanks in Advance!!!!

    Are you using any reporting frameworks like Jasper
    Reports or you using simple select queries in MySQL
    to export the data to CSV format.Detail more clearly
    to get assist from others.
    Are you using Session beans or Entity beans on Weblogic?no no no, he can create the csv file, whether its in the correct format is the problem of the consumer of this csv file, isnt'it?
    are you using a microsoft product?

  • Problem in writing data in file......

    i am having problem in passing a String object path ;
    taken from user in following way
    FileWriter fw = new FileWriter(path,append);
    error is : (The filename, directory name, or volume label syntax is incorrect)
    but if i am using
    FileWriter fw = new FileWriter("f.txt",append);
    it works...
    but i want filename from user... how to achieve this

    class writeData
         public String getName()
                        String name=null;
         try
              char c;
              StringBuffer bf=new StringBuffer();
              System.out.print("Enter the File Name:- ");
              while((c=(char)System.in.read())!='\n')
                   bf.append(c);
              name=bf.toString();
              catch(Exception e)
              System.out.println("Error is:-"+e);
              return name;
    public void wfile(String name1)
              try
              String path ="D:/fname.txt";
              boolean append = true;
              FileWriter fw=new FileWriter(path); // its not working....
              //FileWriter fw=new FileWriter("D:/fname.txt");
              catch(Exception e)
                   System.out.println("Error is :- "+e);
    public class bravo
         public static void main(String args[])
              writeData wd = new writeData();
              String n = wd.getName();
              wd.wfile(n);
    }

  • Problem while writing in a file

    Hi,
    i want to write some bytes in a file but it is producing an error
    error:
    ====
    java.io.FileNotFoundException: C:\Documents and Settings\rrus\My Documents\data.pkcs7data (The system cannot find the path specified)
    code:
    ====
    File obj_file = new File(System.getProperty("user.home")+"/My Documents/Signature.sig");
    if(!obj_file.exists())
    obj_file.createNewFile();
    FileOutputStream obj_fout = new FileOutputStream(obj_file);
    obj_fout.write(m_bData); // m_bData is byte array
    obj_fout.flush();
    obj_fout.close();

    And:
    C:\Documents and Settings\rrus\My Documents\data.pkcs7data
    File obj_file = new File(System.getProperty("user.home")+"/My Documents/Signature.sig");Something doesn't quite match here. Your eror message does not match your code.

  • Problem with writing into txt file on the Web

    Hello friends - please could you give me an advice? Java console says:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission http:\web.telecom.cz\jiriczech\xanado.txt write)
    Thank you a lot in advance:)!!

    The place you are trying to write the file to does not have write permission.

  • Writing in INF file  Problem!

    Hi
    I've successfully read from INF file by the following code :
        public String Read_INI(String Path , String Attribute)
            Properties p = new Properties();
            try
                p.load(new FileInputStream(Path));
            catch (Exception e)
                    System.out.println(e);
            return p.getProperty(Attribute);
        }Now I'm facing a problem in writing in INF file
    i used this code but it doesn't work!
        public void Write_INI(String Value, String Attribute, String Path)
            Properties p = new Properties();
            try
                   p.load(new FileInputStream(Path));
                   p.setProperty(Attribute, Value);
            catch (Exception e)
                    System.out.println(e);
        }any ideas ?

    thnx very much :)
    just i added :
                   p.store(new FileOutputStream(Path), Value);after :
         p.setProperty(Attribute, Value);

  • Writing output to file does not work

    Hello All,
    I have a problem with writing to a file created on the command prompt:
    1) my base class is called TestRandom2
    2) I have a method called run which runs the print method
    3) I passed a reference of the run method into the main below, I don't know if I'm doing it correctly but the error message I'm getting "cannot resolve variable symbol : variable String
    location: class TestRandom2 return String;"
    4)When I declare the method run as void it's also giving an error.
    5)I would to fix this proble to write my output to a .xls file. Can someone help me as soon as possible please!!!!
    public static void main(String[] args) throws Exception {
         TestRandom2 testrandom = new TestRandom2();
              byte b[] = new String(testrandom.run()).getBytes();
              OutputStream o = new FileOutputStream(args[0]);
              o.write(b);
              o.close();
         }

    this is my entire file, I want to be able to call the run method in main and have the file out put to an xls file can some one help me please
    Code ------
    import java.io.*;
    public class TestRandom2{
         Deck deck = new Deck();
         public TestRandom2(){
              deck.populate();
         public void run(String file){
                   if(file.equals("") || file==null)
                   throws IOException {
                   FileOutputStream output=new FileOutputStream(file);
                   for(int i=0; i<5; i++){
                   deck.shuffle();
                   deck.print();
                   output.close;
         class Deck{
              public void populate(){
                   System.out.println("populating deck!");
                   cards=new Integer[52];
                   for(int i=0;i<52;i++){
                        cards= new Integer(i+1);
         public void shuffle(){
              System.out.println("Shuffling deck!");
              rnd.setSeed(randomseed.getSeed());
              java.util.List list = java.util.Arrays.asList(cards);
              java.util.Collections.shuffle(list,rnd);
              cards = (Integer[])list.toArray(new Integer[0]);
         public void print(){
              System.out.println("populating deck!");
              for(int i=0;i<cards.length;i++){
                   System.out.print("P:"+(i+1));
                   System.out.print("C:"+cards[i].intValue());
              Integer[] cards = null;
              RandomSeed randomseed = new RandomSeed();
              java.util.Random rnd = new java.util.Random();
              class RandomSeed {
         private long[] seeds = new long[] {
              9876, 54321,
              1299961164, 253987020,
              669708517, 2079157264,
              190904760, 417696270,
              1289741558, 1376336092,
              1803730167, 324952955,
              489854550, 582847132,
              1348037628, 1661577989,     
              350557787, 1155446919,          
              591502945, 634133404,
              1901084678, 862916278,     
              1988640932, 1785523494,     
              1873836227, 508007031,          
              1146416592, 967585720,
              1837193353, 1522927634,
              38219936, 921609208,
              349152748, 112892610,          
              744459040, 1735807920,
              1983990104, 728277902,
              309164507, 2126677523,
              362993787, 1897782044,
              556776976, 462072869,
              1584900822, 2019394912,
              1249892722, 791083656,          
              1686600998, 1983731097,
              1127381380, 198976625,
              1999420861, 1810452455,
              1972906041, 664182577,          
              84636481, 1291886301,
              1186362995, 954388413,
              2141621785, 61738584,
              1969581251, 1557880415,          
              1150606439, 136325185,
              95187861, 1592224108,
              940517655, 1629971798,
              215350428, 922659102,     
              786161212, 1121345074,
              1450830056, 1922787776,
              1696578057, 2025150487,
              1803414346, 1851324780,          
              1017898585, 1452594263,
              1184497978, 82122239,
              633338765, 1829684974,
              430889421, 230039326,          
              492544653, 76320266,
              389386975, 1314148944,
              1720322786, 709120323,
              1868768216, 1992898523,          
              443210610, 811117710,
              1191938868, 1548484733,
              616890172, 159787986,
              935835339, 1231440405,     
              1058009367, 1527613300,
              1463148129, 1970575097,
              1795336935, 434768675,
              274019517, 605098487,          
              483689317, 217146977,
              2070804364, 340596558,
              930226308, 1602100969,
              989324440, 801809442,          
              410606853, 1893139948,
              1583588576, 1219225407,
              2102034391, 1394921405,
              2005037790, 2031006861,          
              1244218766, 923231061,
              49312790, 775496649,
              721012176, 321339902,
              1719909107, 1865748178,          
              1156177430, 1257110891,
              307561322, 1918244397,
              906041433, 360476981,
              1591375755, 268492659,          
              461522398, 227343256,
              2145930725, 2020665454,
              1938419274, 1331283701,     
              174405412, 524140103,          
              494343653, 18063908,
              1025534808, 181709577,
              2048959776, 1913665637,
              950636517, 794796256,          
              1828843197, 1335757744,
              211109723, 983900607,
              825474095, 1046009991,
              374915657, 381856628,          
              1241296328, 698149463,
              1260624655, 1024538273,
              900676210, 1628865823,
              697951025, 500570753,          
              1007920268, 1708398558,
              264596520, 624727803,
              1977924811, 674673241,
              1440257718, 271184151,          
              1928778847, 993535203,
              1307807366, 1801502463,
              1498732610, 300876954,
              1617712402, 1574250679,          
              1261800762, 1556667280,
              949929273, 560721070,
              1766170474, 1953522912,
              1849939248, 19435166,          
              887262858, 1219627824,
              483086133, 603728993,
              1330541052, 1582596025,
              1850591475, 723593133,          
              1431775678, 1558439000,
              922493739, 1356554404,
              1058517206, 948567762,
              709067283, 1350890215,          
              1044787723, 2144304941,
              999707003, 513837520,
              2140038663, 1850568788,
              1803100150, 127574047,          
              867445693, 1149173981,
              408583729, 914837991,
              1166715497, 602315845,
              430738528, 1743308384,          
              1388022681, 1760110496,
              1664028066, 654300326,
              1767741172, 1338181197,
              1625723550, 1742482745,          
              464486085, 1507852127,
              754082421, 1187454014,
              1315342834, 425995190,
              960416608, 2004255418,          
              1262630671, 671761697,
              59809238, 103525918,
              1205644919, 2107823293,
              1615183160, 1152411412,          
              1024474681, 2118672937,
              1703877649, 1235091369,
              1821417852, 1098463802,
              1738806466, 1529062843,          
              620780646, 1654833544,
              1070174101, 795158254,
              658537995, 1693620426,
              2055317555, 508053916,          
              1647371686, 1282395762,
              29067379, 409683067,
              1763495989, 1917939635,
              1602690753, 810926582,          
              885787576, 513818500,
              1853512561, 1195205756,
              1798585498, 1970460256,
              1819261032, 1306536501,          
              1133245275, 37901,
              689459799, 1334389069,
              1730609912, 1854586207,
              1556832175, 1228729041,
              251375753, 683687209,
              2083946182, 1763106152,
              2142981854, 1365385561,
              763711891, 1735754548,
              1581256466, 173689858,
              2121337132, 1247108250,
              1004003636, 891894307,
              569816524, 358675254,
              626626425, 116062841,
              632086003, 861268491,
              1008211580, 779404957,
              1134217766, 1766838261,
              1423829292, 1706666192,
              942037869, 1549358884,
              1959429535, 480779114,
              778311037, 1940360875,
              1531372185, 2009078158,
              241935492, 1050047003,
              272453504, 1870883868,
              390441332, 1057903098,
              1230238834, 1548117688,
              1242956379, 1217296445,
              515648357, 1675011378,
              364477932, 355212934,
              2096008713, 1570161804,
              1409752526, 214033983,
              1288158292, 1760636178,
              407562666, 1265144848,
              1071056491, 1582316946,
              1014143949, 911406955,
              203080461, 809380052,
              125647866, 1705464126,
              2015685843, 599230667,
              1425476020, 668203729,
              1673735652, 567931803,
              1714199325, 181737617,
              1389137652, 678147926,
              288547803, 435433694,
              200159281, 654399753,
              1580828223, 1298308945,
              1832286107, 169991953,
              182557704, 1046541065,
              1688025575, 1248944426,
              1508287706, 1220577001,
              36721212, 1377275347,
              1968679856, 1675229747,
              279109231, 1835333261,
              1358617667, 1416978076,
              740626186, 2103913602,
              1882655908, 251341858,
              648016670, 1459615287,
              780255321, 154906988,
              857296483, 203375965,
              1631676846, 681204578,
              1906971307, 1623728832,
              1541899600, 1168449797,
              1267051693, 1020078717,
              1998673940, 1298394942,
              1914117058, 1381290704,
              426068513, 1381618498,
              139365577, 1598767734,
              2129910384, 952266588,
              661788054, 19661356,
              1104640222, 240506063,
              356133630, 1676634527,
              242242374, 1863206182,
              957935844, 1490681416 };
         public void longToLong(){
              for (int i=0;i<(seeds.length);i++){
                   seedsArray[i] = new java.lang.Long(seeds[i]);
         public boolean checkForSeed(long seed){
              for(int i=0;i<lastSeed.length;i++){
                   if (seed == lastSeed[i])
                        return true;
              addSeed(seed);
              return false;
         public void addSeed(long seed){     
              if (!(currentseedpos < maxSeeds))
                   currentseedpos = 0;
              lastSeed[currentseedpos] = seed;
         public boolean checkForValue(int value){
              for(int i=0;i<lastValue.length;i++){
                   if (value == lastValue[i])
                        return true;
                   addValue(value);
                   return false;
         public void addValue(int value){
              if (!(currentvaluepos < maxValues))
                   currentvaluepos = 0;
              lastValue[currentvaluepos] = value;
         public RandomSeed(){
              lastValue = new int[maxValues];
              lastSeed = new long[maxSeeds];
              longToLong();
              shuffle();
         public RandomSeed(int v){
              maxValues = v;
              lastValue = new int[maxValues];
              lastSeed = new long[maxSeeds];
              longToLong();
              shuffle();
         public RandomSeed(int v, int s){
              maxValues = v;
              maxSeeds = s;
              lastValue = new int[maxValues];
              lastSeed = new long[maxSeeds];
              longToLong();
              shuffle();
         public void shuffle(){
              random.setSeed(seeds[random.nextInt(seeds.length-1)]);
              java.util.List list = java.util.Arrays.asList(seedsArray);
              java.util.Collections.shuffle(list,random);
         public long getSeed(){
              shuffle();
              random.setSeed(seeds[random.nextInt(seeds.length-1)]);
              long seed=seedsArray[random.nextInt(seeds.length-1)].longValue();
              while (checkForSeed(seed))seed=seedsArray[random.nextInt(seeds.length-1)].longValue();
              return seed;
         public int nextInt(int max){
              shuffle();
              random.setSeed(seeds[random.nextInt(seeds.length-1)]);
              long seed = seedsArray[random.nextInt(seeds.length-1)].longValue();
              while (checkForSeed(seed))
                   seed = seedsArray[random.nextInt(seeds.length-1)].longValue();
                   random.setSeed(seed);
                   int seedone = random.nextInt(max)+1;
                   if (checkForValue(seedone))
                   seedone = random.nextInt(max)+1;
                   return (seedone);
         public int nextInt(){
              return nextInt(MAXINT);
         }     private int currentseedpos = 0;
         private int currentvaluepos = 0;
         public int lastValue[] = new int[0];
         public long lastSeed[] = new long[0];
         public final int MAXINT = 9999;
         public int maxSeeds = 400;
         public int maxValues = 5;
         private java.lang.Long[] seedsArray = new java.lang.Long[seeds.length];
         private java.util.Random random = new java.util.Random();
         public static void main(String[] args) throws Exception {
         TestRandom2 testrandom = new TestRandom2();
              testrandom.run();
    ----Code
    Thanks for all the response I've been getting please continue to help

  • Problem in reading no. of files and writing into a single file

    Hi,
    Iam with Problem in reading no. of files and writing into a single file....
    Iam reading no. of files stored in local directory.......
    Iam able to read and print the data in files successfully....but while writing..only first file is being written...and the next files are not written in my output file...
    plz tell me my mistake....I hope Iam doing some mistake while writing into file...PLz help.....
    Basically my code structure is like this....
    import java.io.*;
    import java.util.regex.*;
    import java.util.*;
    import java.text.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    class Writing {
    public static void main(String args[]) throws Exception {
              FileOutputStream fileOut = new FileOutputStream("ServerResult.xls"); //my output file
              int counter = 1;
              File dir = new File("C:/Perform/ServerLogs");
              String[] children = dir.list();
              if( children == null)
                   System.out.println("The Directory mentioned does not exist");
              else {
                   for (int fileNo = 0; fileNo < children.length; fileNo++ ) {        //Files iteration starts
                        String filename = children[fileNo];
              File logFile = new File(filename);
    FileReader logFileReader = new FileReader(logFile);
    BufferedReader logReader = new BufferedReader(logFileReader);
    StringBuffer sBuf = new StringBuffer(5000);
              HSSFWorkbook wb = new HSSFWorkbook();          
              HSSFSheet sheet = wb.createSheet();
              HSSFRow rowTitle;
              HSSFRow rowReq;
              HSSFRow rowRes;
    String aLine = null;
    boolean skip = false;
    boolean readed = false;
    boolean initReq = false;
              boolean flag = false;
    long requestTime = 0;
    long responseTime = 0;
    long recdTime = 0;
    long sentTime = 0;
              long hasTime = 0;
              long presentTime = 0;
              int hasCalls = 0;
    Pattern startMessage = Pattern.compile("^<MESSAGE.*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern requestMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<ActName>(.*)</ActName>.*", Pattern.DOTALL);
    Pattern requestMessage1 = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<Svc id=\"(.*)\">.*", Pattern.DOTALL);
    Pattern responseMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern initMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"HostConnInit\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern initResMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*", Pattern.DOTALL);
    Pattern initResIDMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*<IATA>"+args[0]+"</IATA>.*", Pattern.DOTALL);
              Pattern sentMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgSentInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
              Pattern rcvdMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgRcvdInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    DecimalFormat dcf = new DecimalFormat("########.##");
    String actName = "";
              if (fileNo ==0)
              rowTitle = sheet.createRow((short)0);
              rowTitle.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)0).setCellValue("Req/Res");
              rowTitle.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)1).setCellValue("Action");
              rowTitle.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)2).setCellValue("Server Time(in ms)");
              rowTitle.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)3).setCellValue("Request Vs Response Time in Server(in ms)");
              rowTitle.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)4).setCellValue("Time Taken By HAS/HOST(in ms)");
              rowTitle.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)5).setCellValue("No. of HAS calls");
              rowTitle.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)6).setCellValue("Data Size");
              //wb.write(fileOut);
    while((aLine=logReader.readLine()) != null) {
    if(aLine.startsWith("<MESSAGE TYPE=\"EVENT\"")) {
    Matcher m = startMessage.matcher(aLine);
    if(m.find()) {
    sBuf.setLength(0);
    sBuf.append(aLine);
    skip = false;
    initReq = false;
    m = initMessage.matcher(aLine);
    if(m.find()) {
    initReq = true;
    } else {
    if(initReq) {
    m = initResMessage.matcher(aLine);
    if(m.find()) {
    sBuf.setLength(0);
    sBuf.append(aLine);
    skip = false;
    } else if(aLine.startsWith("</MESSAGE>")) {
    if(!skip) {
    sBuf.append(aLine);
    readed = true;
    } else if(!skip){
    sBuf.append(aLine);
    if(!skip && readed) {
    String tempStr = sBuf.toString();
    if(tempStr.length() > 0) {
    boolean reqMatched = false;
    Matcher m = null;
    if(initReq) {
    m = initMessage.matcher(tempStr);
    actName = "Intialization";
    } else {
    m = requestMessage.matcher(tempStr);
    String time = "";
    if(m.find()) {
    reqMatched = true;
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    if(i == 1) {
    time = groupStr;
    } else if(i == 2) {
    actName = groupStr;
    } else if(!initReq){
    m = requestMessage1.matcher(tempStr);
    if(m.find()) {
    reqMatched = true;
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    if(i == 1) {
    time = groupStr;
    } else if(i == 2) {
    actName = groupStr;
    if(time.length() > 0 ) {
    try{
    requestTime = sdf.parse(time).getTime();
    }catch(Exception ex){}
    System.out.println("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
                                  //bw.write("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
                                  String reqDataSize = dcf.format(((double)time.length()/1024.0))+"K" ;
                                  rowReq = sheet.createRow((short)counter);
                                       rowReq.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)0).setCellValue("Request");
                                       rowReq.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)1).setCellValue(actName);
                                       rowReq.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)2).setCellValue(time);
                                       rowReq.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)3).setCellValue("");
                                       rowReq.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)4).setCellValue("");
                                       rowReq.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)5).setCellValue("");
                                       rowReq.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)6).setCellValue(reqDataSize);
                                       counter = counter +1;
                                       System.out.println("counter is "+counter);
                             Matcher l = sentMessage.matcher(tempStr);
                             Matcher k = rcvdMessage.matcher(tempStr);
                   if(l.find()) {
                                            for (int i=1; i<=l.groupCount(); i++) {
         String groupStr2 = l.group(i);
    try{
    sentTime = sdf.parse(groupStr2).getTime();
    }catch(Exception ex){}
                        if(k.find())
                                                 for(int j=1;j<=k.groupCount(); j++) {
                                                 String groupStr1 = k.group(j);
                                                 try{
    recdTime = sdf.parse(groupStr1).getTime();
    }catch(Exception ex){}
                                                 presentTime = (recdTime - sentTime);
                                                 hasTime = hasTime + presentTime;
                                                 hasCalls = hasCalls +1;
    if(!reqMatched) {
    if(initReq) {
    m=initResIDMessage.matcher(tempStr);
    } else {
    m=responseMessage.matcher(tempStr);
    if(m.find()) {
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    try{
    responseTime = sdf.parse(groupStr).getTime();
    }catch(Exception ex){}
                                                 String resDataSize = dcf.format(((double)tempStr.length()/1024.0))+"K" ;
                                                 rowRes = sheet.createRow((short)(counter));
                                                 rowRes.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)0).setCellValue("Response");
                                                 rowRes.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)1).setCellValue(actName);
                                                 rowRes.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)2).setCellValue(groupStr);
                                                 rowRes.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)3).setCellValue((responseTime - requestTime));
                                                 rowRes.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)4).setCellValue(hasTime);
                                                 rowRes.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)5).setCellValue(hasCalls);
                                                 rowRes.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)6).setCellValue(resDataSize);
                                                 hasTime = 0;
                                                 hasCalls = 0;
                                                 counter = counter + 1 ;
    sBuf.setLength(0);
    readed = false;
              wb.write(fileOut);
              } // End of for (int fileNo = 0; fileNo < children.length; fileNo++ )
    }     //End of else
              fileOut.close();
    } //End of public static void main
    } // End of Class

    First of all, use [code]-tags to make your code readable, please.
    I didn't do a complete inspection of your code (because it's too much and unreadable as it is) and I don't know POI, but creating a new HSSFWorkbook for each input file sounds fishy to me ... try re-using the workbook and just creating a new sheet in each iteration.

  • Problem while writing to fixed length flat file from xml

    Hi,
    I have a problem in writing data into a flat file of fixed length...
    My input is a xml file and i want the output as a flat file. I am successful in converting the xml into flat file... But the main problem is, i am unable to insert spaces in between my fields in the flat file.
    The data in the flat file comes without spaces... Any suggestions on writing the schema...
    Regards
    Surya.

    Have a look at this doc
    http://otndnld.oracle.co.jp/document/products/as10g/101310/doc_cd/integrate.1013/b28994/nfb.htm#BGBBAJFD
    your element should be something like this, it pads with a space using the paddedBy expression
    <xsd:element name="C1" type="xsd:string" nxsd:style="fixedLength" nxsd:length="4" nxsd:paddedBy=" " nxsd:padStyle="tail" />if having trouble post what you want the file to look like, and the xsd you are using.
    cheers
    James

  • Error writing to temporary file location. If this problem persists contact customer support. (-70)

    I've been trying to update/install Creative Cloud applications via Adobe Application Manager and no matter which application I try to install I receive this error: "Error writing to temporary file location. If this problem persists contact customer support. (-70)"
    Prior to this I was having trouble running updates to an application, and it told me I needed "Administrative Privleges" to do so. I have tried everything I can think of with the assistance of the Apple Store. Can anyone at Adobe help me?

    You do not have the permission on the TMP folder for write because of which you are facing the issue.
    Tmp folder is hidden on the Mac hence you have to unhide it first to check the permission and getting it corrected.
    I would recommend you to check the install/update from
    1) New user account
    2) Run the Disk repair utitlity
    if these steps doesn't help then contact support to get the permission corrected.

  • Problem writing to a file on a shared drive

    I am having problems with my application not writing to a file on a shared drive. Actually it works perfect on one computer, but not on any other computer. Any ideas on why this would not work. Here is my code below, I think this may be an issue with permissions on the shared drive but have played with those until I am sick of it and nothing works. Any help on getting it to write to a file on a shared drive would be great.
    report2 = new JButton("Provider Order Entry");
                        report2.addActionListener(new ActionListener() {
                             public void actionPerformed (ActionEvent e) {
                                  if (e.getSource() == report2) {
                                       try {
                                            File file = new File("z:\\Provider Order Entry Reports\\ACCESSFILE.RMD");
                                            FileReader checkAccess = new FileReader(file);
                                            BufferedReader checkAccessBuff = new BufferedReader(checkAccess);
                                            boolean eof = false;
                                            while (!eof) {
                                                 String line = checkAccessBuff.readLine();
                                                 if (line != null) {
                                                      eof = true;
                                                      checkAccess.close();
                                                      checkAccessBuff.close();
                                                      if (!poeSelectionWindow.isShowing()) {
                                                           poeSelectionWindow.setSize(575, 200);
                                                           poeSelectionWindow.setBackground(blue);
                                                           JFrame.setDefaultLookAndFeelDecorated(false);
                                                           poeSelectionWindow.setVisible(true);
                                                      else if (poeSelectionWindow.isShowing()) {
                                                           poeSelectionWindow.setVisible(false);
                                       catch (IOException error) {
                                            Component controllingFrame = null;
                                            JOptionPane.showMessageDialog(controllingFrame,
                                                       "YOU DO NOT HAVE ACCESS TO THIS OPTION" + "\n" +
                                                       "PLEASE CONTACT IRM SUPPORT TO REQUEST ACCESS ",
                                                       "ACCESS DENIED",
                                                       JOptionPane.ERROR_MESSAGE);
                                            try {
                                                 File errorFile = new File("Z:\\LOG\\LOGGER.log");
                                                 String username = System.getProperty("user.name");
                                                 InetAddress addr = InetAddress.getLocalHost();
                                                 Date date = new Date();
                                                 BufferedWriter bw = new BufferedWriter(new FileWriter(errorFile, true));
                                               bw.write("ACCESS ATTEMPTED ON: Provider Order Entry Report BY:" + username + " At Workstation/IP: "
                                                         + addr + " " + date);
                                               bw.newLine();
                                               bw.flush();
                                               bw.close();
                                            catch (IOException error1) {
                                                 System.out.println("Error-- " + error1.toString());
                                            catch (NullPointerException NPE) {
                                                 System.out.println("Error -- " + NPE.toString());                                                       
                                       catch (NullPointerException NPE) {
                                            System.out.println("Error -- " + NPE.toString());                                                       
                        });

    So how do I stop the
    NPE from occurring.By not dereferencing a null reference.
    Thingamabob xyz = doSomethingWhichMightReturnNull();
    if (xyz != null)
    // go ahead and use xyz here
    If you leave out the above "if" statement check, and just willy-nilly try to use xyz when it is null, you'll get the NPE.
    It is occurring on the file
    name. I have never been able to stop the file name
    from throwing a NPE.I don't know how that translates to some lines of your code.

  • Problems with writing to file, and with ActionListener.

    I have been trying to write a Payroll Division type program as my school Computer Science Project. However, I have a few problems with it...
    import java.io.IOException;
    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.StringTokenizer;
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.*;
    public class Personnel implements ActionListener  {    
             JFrame GUIFrame;
             JLabel ID, Line, OKText,AnswerField;
             JTextField IDField, LineField;
             JButton OK;
             JPanel GUIPanel;
             int trialCounter=0;
             final static int employeeNumber = 7;
             final static int maxValue = ((employeeNumber*4)-1);
            //Number of employees, which would be in real life passed by the Payroll division.   
            public static String [][] sortHelp = new String [employeeNumber+1][3];    /** Creates a new instance of Personnel */       
            public Personnel() {
              GUIFrame = new JFrame("PersonnelSoft"); //create title header.
                     GUIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                     GUIFrame.setSize(new Dimension(100, 140));
                     GUIPanel= new JPanel(new GridLayout(2, 2));
                     addWidgets();
                     GUIFrame.getRootPane().setDefaultButton(OK);
                     GUIFrame.getContentPane().add(GUIPanel, BorderLayout.CENTER);
                     GUIFrame.pack();
                    GUIFrame.getContentPane().setVisible(true);
                    GUIFrame.setVisible(true);
            private void addWidgets() {
                  ID = new JLabel ("Please enter your employee Identification Number:", SwingConstants.LEFT);
                  IDField = new JTextField ("ID", 5);
                  Line = new JLabel ("Please enter the line of your payroll with which you have concerns:", SwingConstants.LEFT);
                  LineField = new JTextField ("###", 2);
                  OKText = new JLabel ("Click OK when you have verified the validity of your request", SwingConstants.LEFT);
                  OK = new JButton ("OK");
                  OK.setVerticalTextPosition(AbstractButton.CENTER);
                  OK.setMnemonic(KeyEvent.VK_I);
                  AnswerField = new JLabel("The Result of your Querie will go here", SwingConstants.LEFT);
                  GUIPanel.add(ID);
                  GUIPanel.add(IDField);
                  GUIPanel.add(Line);
                  GUIPanel.add(LineField);
                  GUIPanel.add(OKText);
                  GUIPanel.add(OK);
                  GUIPanel.add(AnswerField);
                  OK.addActionListener(this);
                  ID.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  OKText.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  Line.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            public static void ArrayCreate() throws IOException {   
              //creates a employeeNumber x 3 array, which will hold all data neccessary for future sorting by employee ID number.      
              int counter = 2;      
              int empCounter = 1;      
              String save;
              //avoid having to waste memory calculating this value every time the for loop begins 
              FileInputStream inFile = new FileInputStream("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR.txt"); 
              BufferedReader in = new BufferedReader(new InputStreamReader(inFile));
              String line;
                    line = in.readLine();
                    StringTokenizer st = new StringTokenizer(line);
                    save = st.nextToken();
                    sortHelp[0][0] = save;
                    sortHelp[0][2] = save;
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[0][1] = save;
                    while (counter <= maxValue) {
                    line = in.readLine();
                    if (((counter - 1) % 4) == 0) {
                    st = new StringTokenizer(line);
                    sortHelp[empCounter][0] = st.nextToken();
                    sortHelp[empCounter][2] = sortHelp[empCounter][0];
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[empCounter][1] = save;
                    empCounter++;
                    counter++;
                 public static String[] joinString() {
                      String[] tempStorage = new String[employeeNumber+1];
                      int counter;
                      for (counter = 0; counter <= employeeNumber; counter++) {
                           tempStorage[counter] = (sortHelp[counter][1] + sortHelp[counter][0]);
                      return (tempStorage);
                 public static String[] sortEm(String[] array, int len)
                     java.util.Arrays.sort(array);
                     return array;
                 public static void splitString(String[] splitString){
                    int counter;
                    for (counter = 0; counter <= employeeNumber; counter++){
                         sortHelp[counter][0]=splitString[counter].substring( 5 );
                         sortHelp[counter][1]=splitString[counter].substring(0,5);
                 void setLabel(String newText) {
                     AnswerField.setText(newText);
                 void writetoHR(String local) throws IOException {
                      FileOutputStream outFile = new FileOutputStream ("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR2.txt");
                       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outFile));
                       out.write(local+"the preceding employee number is not in our database, but has submitted a request. Please sort out the issue");
                       System.exit(0);
                 public void actionPerformed(ActionEvent e){
                      boolean flag=false;
                      String local=IDField.getText();
                      int i=0;
                      while((i<=employeeNumber)&&(flag==false)){
                           if (sortHelp[1]==local) {
                   flag=true;
              i++;
         trialCounter++;
         if (trialCounter>=3)
              writetoHR(local);
         if (flag==false)
              setLabel("Your ID number does not exist in our records. Verify your ID and try again.");
         else {
              switch (LineField.getText())
              case 04:
                   setLabel("Your pay is calculated by multiplying your working hours by the amount per hour. If both of these fields are satisfactory to you, please contact humanresource");
                   break;
              case 03:
                   setLabel("Hourly amount was calculated by the system, by dividing your yearly pay 26 and then 80.");
                   break;
              case 07:
                   setLabel("Overtime pay was calculated by multiplying regular hourly pay by 1.1");
                   break;
              case 06:
                   setLabel("The overtime hourly pay was multiplied by the amount of overtime hours.");
                   break;
              case 10:
                   setLabel("For holiday hours, your pay is increased by 25%.");
                   break;
              case 09:
                   setLabel("The holiday hourly pay was multiplied by your amount of holiday hours.");
                   break;
              case 11:
                   setLabel("Your total pay was calculated by adding all the separate types of payment to your name.");
                   break;
              case 17:
                   setLabel("Your net pay was found by subtracting the amount withheld from your account");
                   break;
              case 19:
                   setLabel("Your sick hours remaining were taken from a pool of 96 hours.");
                   break;
              default:
                   setLabel("Please contact humanresource.");
              break;
    private static void CreateAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    Personnel GUI = new Personnel();
         public static void main(String[] args) throws IOException {
              String[] temporary = new String[employeeNumber];
              ArrayCreate();
    temporary = joinString();
    temporary = sortEm(temporary, employeeNumber);
    splitString(temporary);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    CreateAndShowGUI();
    int row;
    int column;
         for (row = 0; row < (employeeNumber); row++) {    // verify proper output by ArrayCreate splitString
    for (column = 0; column <= 2; column++) {
    System.out.print(sortHelp[row][column]);
    System.out.print(' ');
    System.out.print(' ');
    System.out.println();
    1) It does not permit me to switch on a String. How do I solve that?
    2)How would I throw an exception (IO) within actionperformed?
    3)Generally, if cut it down to everything except the writing to a file part, the actionperformed script causes an error... why?
    Thanks in advance.
    And sorry for the relative lameness of my question...
    ---abe---

    Thank you very much. That did solve almost all the problems that I had...
    I just have one more problem.
    First (here's the new code):
    import java.io.IOException;
    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.StringTokenizer;
    import javax.swing.*;
    import java.util.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.*;
      public class Personnel implements ActionListener  {    
             JFrame GUIFrame;
              JLabel ID, Line, OKText,AnswerField;
               JTextField IDField, LineField;
               JButton OK;
               JPanel GUIPanel;
               int trialCounter=0;
         final static int employeeNumber = 7;
         final static int maxValue = ((employeeNumber*4)-1);
                public static String [][] sortHelp = new String [employeeNumber+1][3];   
         public Personnel() {
              GUIFrame = new JFrame("PersonnelSoft"); //create title header.
             GUIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             GUIFrame.setSize(new Dimension(100, 140));
             GUIPanel= new JPanel(new GridLayout(2, 2));
             addWidgets();
             GUIFrame.getRootPane().setDefaultButton(OK);
             GUIFrame.getContentPane().add(GUIPanel, BorderLayout.CENTER);
             GUIFrame.pack();
            GUIFrame.getContentPane().setVisible(true);
            GUIFrame.setVisible(true);
            private void addWidgets() {
                  ID = new JLabel ("Please enter your employee Identification Number:", SwingConstants.LEFT);
                  IDField = new JTextField ("ID", 5);
                  Line = new JLabel ("Please enter the line of your payroll with which you have concerns:", SwingConstants.LEFT);
                  LineField = new JTextField ("###", 2);
                  OKText = new JLabel ("Click OK when you have verified the validity of your request", SwingConstants.LEFT);
                  OK = new JButton ("OK");
                  OK.setVerticalTextPosition(AbstractButton.CENTER);
                  OK.setMnemonic(KeyEvent.VK_I);
                  AnswerField = new JLabel("The Result of your Querie will go here", SwingConstants.LEFT);
                  GUIPanel.add(ID);
                  GUIPanel.add(IDField);
                  GUIPanel.add(Line);
                  GUIPanel.add(LineField);
                  GUIPanel.add(OKText);
                  GUIPanel.add(OK);
                  GUIPanel.add(AnswerField);
                  OK.addActionListener(this);
                  ID.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  OKText.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  Line.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            public static void ArrayCreate() throws IOException {   
              int counter = 2;      
              int empCounter = 1;      
              String save;
              FileInputStream inFile = new FileInputStream("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR.txt"); 
              BufferedReader in = new BufferedReader(new InputStreamReader(inFile));
              String line;
                    line = in.readLine();
                    StringTokenizer st = new StringTokenizer(line);
                    save = st.nextToken();
                    sortHelp[0][0] = save;
                    sortHelp[0][2] = save;
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[0][1] = save;
                    while (counter <= maxValue) {
                    line = in.readLine();
                    if (((counter - 1) % 4) == 0) {
                    st = new StringTokenizer(line);
                    sortHelp[empCounter][0] = st.nextToken();
                    sortHelp[empCounter][2] = sortHelp[empCounter][0];
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[empCounter][1] = save;
                    empCounter++;
                    counter++;
                 public static String[] joinString() {
                      String[] tempStorage = new String[employeeNumber+1];
                      int counter;
                      for (counter = 0; counter <= employeeNumber; counter++) {
                           tempStorage[counter] = (sortHelp[counter][1] + sortHelp[counter][0]);
                      return (tempStorage);
                 public static String[] sortEm(String[] array, int len)
                     java.util.Arrays.sort(array);
                     return array;
                 public static void splitString(String[] splitString){
                    int counter;
                    for (counter = 0; counter <= employeeNumber; counter++){
                         sortHelp[counter][0]=splitString[counter].substring( 5 );
                         sortHelp[counter][1]=splitString[counter].substring(0,5);
                 void setLabel(String newText) {
                     AnswerField.setText(newText);
                 void writetoHR(String local) throws IOException {
                      FileOutputStream outFile = new FileOutputStream ("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR2.txt");
                       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outFile));
                       out.write(local+"the preceding employee number is not in our database, but has submitted a request. Please sort out the issue");
                       System.exit(0);
                 public void actionPerformed(ActionEvent e){
                      boolean flag=false;
                      String local=IDField.getText();
                      local trim();
                      int i=0;
                      while((i<employeeNumber)&&(flag==false)){
                           if (sortHelp[1]==local) {
                   flag=true;
              else {
         i++;
         trialCounter++;
         if (trialCounter>=3)
              try {
                   writetoHR(local);
              } catch (IOException exception) {
    setLabel("We are sorry. The program has encountered an unexpected error and must now close");
              } finally {
         if (flag==false)
              setLabel("Your ID number does not exist in our records. Verify your ID and try again.");
         else {
              final Map m = new HashMap();
              m.put("04","Your pay is calculated by multiplying your working hours by the amount per hour. If both of these fields are satisfactory to you, please contact humanresource.");
              m.put("03", "Hourly amount was calculated by the system, by dividing your yearly pay 26 and then 80.");
              m.put("07", "Overtime pay was calculated by multiplying regular hourly pay by 1.1");
              m.put("06", "The overtime hourly pay was multiplied by the amount of overtime hours.");
              m.put("10", "For holiday hours, your pay is increased by 25%.");
              m.put("09", "The holiday hourly pay was multiplied by your amount of holiday hours.");
              m.put("11", "Your total pay was calculated by adding all the separate types of payment to your name.");
              m.put("17", "Your net pay was found by subtracting the amount withheld from your account.");
              m.put("19", "Your sick hours remaining were taken from a pool of 96 hours.");
    setLabel(m.get(LineField.getText()));
    private static void CreateAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    Personnel GUI = new Personnel();
    public static void main(String[] args) throws IOException {
              String[] temporary = new String[employeeNumber];
              ArrayCreate();
    temporary = joinString();
    temporary = sortEm(temporary, employeeNumber);
    splitString(temporary);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    CreateAndShowGUI();
    int row;
    int column;
         for (row = 0; row < (employeeNumber); row++) {    // verify proper output by ArrayCreate splitString
    for (column = 0; column <= 2; column++) {
    System.out.print(sortHelp[row][column]);
    System.out.print(' ');
    System.out.print(' ');
    System.out.println();
    Now that code above produces two errors. First of all.
    local trim();produces the error:
    Syntax error, insert "AssignmentOperator ArrayInitializer" to complete ArrayInitializerAssignementSecondly, if I take that into comments, the line
    setLabel(m.get(LineField.getText()));Produces the error:
    The method setLabel(String) in the type Personnel is not applicable for the arguments (Object)If anybody could help me solve these, I would be sincerely thankfull.
    Now, before anybody asks as to why I want to trim the String in the first place, it is due to the fact that I compare it to another String that is without whitespaces. Thus the field that DOES have whitespaces was preventing me from launching into the if loop:
    if (sortHelp[1]==local) {
                   flag=true;
    (within actionperformed) Or at least that's my explanation as to why the loop never launched. If it is wrong, can somebody please explain?)
    I apologize for the horrible indentation and lack of comments. This is an unfinished version.. I'll be adding the comments last (won't that be a joy), as well as looking for things to cut down on and make the program more efficient.
    Anyways,
    Thanks in Advance,
    ---abe---

  • New to Applets: Problems wiht writing to files and with scroll panes.

    Hi, I've recently graduated from university and so I have limited experience in java programming and I'm having some trouble with JApplets (this is the first time I've made one). I'm trying to make a simple program that will allow users to pick one of a few background images from a list (a list of jpanels within a scroll pane) then at the click of a button will output a CSS with the background tag set to the image location. This is for use on a microsoft sharepoint site where each user has a My-Sit area which I want to be customizable.
    So far I've been creating this program as an application rather than a JApplet and just having another class that extends the JApplet Class which then displays the JFrame from the GUI Class. This initially didnt work because I was trying to add a window to a container so I kept programming it as an application until I got it working before trying to convert it to a JApplet. I solved the previous problem by changing my GUI class to extend JPanel instead of JFrame and it now displays correctly but with a coupe of issues.
    Firstly the applet will not create/write to the CSS file. I read that applets couldnt read/write to the users file system but they could to their own. The file I wish to write to is kept on the same machine as the applet so I'm not sure why this isn't working.
    Secondly the scroll panel is no longer working properly. This worked fine when I was still running the program as an application when the GUI still extended JFrame instead of JPanel (incidentally the program no longer runs as an application in this state) but now the scroll bar does not appear. This is a problem since I want the applet to remain the same size on the page even if I decide to add more backgrounds to the list. I tried setting the applet height/width to smaller values in the html file to see if the scroll bar would appear if the area was smaller than the GUI should be, but this just meant the bottom off the applet was cut off.
    Could anyone offer any suggestion as to why these thigns arnt working and how to fix them? If necessary I can post my source code here. Thanks in advance.

    Ok, well my program is made up of 4 classes, I hope this isnt too much to be posting. If any explaination is needed then I'll post that next. Theres lots of print lines scattered aroudn due to me trying to fix this and theres some stuff commented out from when the program used to be an application isntead of an applet.
    GUI Class, this was the main class until I made a JApplet Class
    public class AppletGUI extends JPanel{
        *GUI Components*
        //JFrames
        JFrame mainGUIFrame = new JFrame();
        JFrame changeBackgroundFrame = new JFrame();
        //JPanels (Sub-panels are indented)
        JPanel changeBackgroundJP = new JPanel(new BorderLayout());
            JPanel changeBackgroundBottomJP = new JPanel(new GridLayout(1,2));
        JPanel backgroundJP = new JPanel(new GridLayout(1,2));
        JPanel selectBackground = new JPanel(new GridLayout(1,2));
        //Jbuttons
        JButton changeBackgroundJB = new JButton("Change Background");
        JButton defaultStyleJB = new JButton("Reset Style");
        //JLabels
        JLabel changeBackgroundJL = new JLabel("Choose a Background from the Menu");
        JLabel backgroundJL = new JLabel();
        //JScrollPane
        JScrollPane backgroundList = new JScrollPane();
            JPanel backgroundListPanel = new JPanel(new GridLayout());
        //Action Listeners
        ButtonListener bttnLstnr = new ButtonListener();
        //Controllers
        CSSGenerator cssGenerator = new CSSGenerator();
        Backgrounds backgroundsController = new Backgrounds();
        backgroundMouseListener bgMouseListener = new backgroundMouseListener();
        //Flags
        Component selectedComponent = null;
        *Colour Changer*
        //this method is used to change the colour of a selected JP
        //selected JPs have their background darkered and when a
        //different JP is selected the previously seleced JP has its
        //colour changed back to it's original.
        public void changeColour(JPanel theJPanel, boolean isDarker){
        //set selected JP to a different colour
        Color tempColor = theJPanel.getBackground();
            if(isDarker){
                tempColor = tempColor.darker();
            else{
                tempColor = tempColor.brighter();
            theJPanel.setBackground(tempColor);
         //also find any sub-JPs and change their colour to match
         int j = theJPanel.getComponents().length;
         for(int i = 0; i < j; i++){
                String componentType = theJPanel.getComponent(i).getClass().getSimpleName();
                if(componentType.equals("JPanel")){
                    theJPanel.getComponent(i).setBackground(tempColor);
        *Populating the GUI*
        //backgroundList.add();
        //Populating the Backgrounds List
        *Set Component Size Method*
        public void setComponentSize(Component component, int width, int height){
        Dimension tempSize = new Dimension(width, height);
        component.setSize(tempSize);
        component.setMinimumSize(tempSize);
        component.setPreferredSize(tempSize);
        component.setMaximumSize(tempSize);     
        *Constructor*
        public AppletGUI() {
            //REMOVED CODE
            //AppletGUI.setDefaultLookAndFeelDecorated(true);
            //Component Sizes
            //setComponentSize
            //Adding Action Listeners to Components
            System.out.println("adding actions listeners to components");
            changeBackgroundJB.addActionListener(bttnLstnr);
            defaultStyleJB.addActionListener(bttnLstnr);
            //Populating the Change Background Menu
            System.out.println("Populating the window");
            backgroundsController.populateBackgroundsData();
            backgroundsController.populateBackgroundsList();
            //loops to add background panels to the JSP
            ArrayList<JPanel> tempBackgroundsList = new ArrayList<JPanel>();
            JPanel tempBGJP = new JPanel();
            tempBackgroundsList = backgroundsController.getBackgroundsList();
            int j = tempBackgroundsList.size();
            JPanel backgroundListPanel = new JPanel(new GridLayout(j,1));
            for(int i = 0; i < j; i++){
                tempBGJP = tempBackgroundsList.get(i);
                System.out.println("Adding to the JSP: " + tempBGJP.getName());
                //Add Mouse Listener
                tempBGJP.addMouseListener(bgMouseListener);
                backgroundListPanel.add(tempBGJP, i);
            //set viewpoing
            backgroundList.setViewportView(backgroundListPanel);
            /*TESTING
            System.out.println("\n\n TESTING!\n Printing Content of SCROLL PANE \n");
            j = tempBackgroundsList.size();
            for(int i = 0; i < j; i++){
                System.out.println(backgroundList.getComponent(i).getName());
            changeBackgroundJP.add(changeBackgroundJL, BorderLayout.NORTH);
            changeBackgroundJP.add(backgroundList, BorderLayout.CENTER);
            //changeBackgroundJP.add(tempBGJP, BorderLayout.CENTER);
            changeBackgroundJP.add(changeBackgroundBottomJP, BorderLayout.SOUTH);
            changeBackgroundBottomJP.add(changeBackgroundJB);
            changeBackgroundBottomJP.add(defaultStyleJB);
            System.out.println("Finsihed populating");
            //REMOVED CODE
            //adding the Background Menu to the GUI and settign the GUI options
            //AppletGUI.setDefaultLookAndFeelDecorated(true);
            //this.setResizable(true);
            //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLocation(500,500);
            this.setSize(400,300);
            this.add(changeBackgroundJP);
        //REMOVED CODE
         *Main Method*
        public static void main(String[] args){
           System.out.println("Creating GUI");
           AppletGUI theGUI = new AppletGUI();
           theGUI.setVisible(true);
           System.out.println("GUI Displayed");
         *Button Listener Inner Class*
        public class ButtonListener implements ActionListener{
            //check which button is clicked
            public void actionPerformed(ActionEvent event) {
                AbstractButton theButton = (AbstractButton)event.getSource();
                //Default Style Button
                if(theButton == defaultStyleJB){
                    System.out.println("Default Style Button Clicked!");
                //Change Background Button
                if(theButton == changeBackgroundJB){
                    System.out.println("Change Background Button Clicked!");
                    String backgroundURL = cssGenerator.getBackground();
                    if(backgroundURL != ""){
                        cssGenerator.setBackgroundChanged(true);
                        cssGenerator.setBackground(backgroundURL);
                        cssGenerator.outputCSSFile();
                        System.out.println("Backgroudn Changed, CSS File Written");
                    else{
                        System.out.println("No Background Selected");
         *Mouse Listener Inner Class*
        public class backgroundMouseListener implements MouseListener{
            public void mouseClicked(MouseEvent e){
                //get component
                JPanel tempBackgroundJP = new JPanel();
                tempBackgroundJP = (JPanel)e.getComponent();
                System.out.println("Background Panel Clicked");
                //change component colour
                if(selectedComponent == null){
                    selectedComponent = tempBackgroundJP;
                else{
                    changeColour((JPanel)selectedComponent, false);
                    selectedComponent = tempBackgroundJP;
                changeColour((JPanel)selectedComponent, true);
                //set background URL
                cssGenerator.setBackground(tempBackgroundJP.getName());
            public void mousePressed(MouseEvent e){
            public void mouseReleased(MouseEvent e){
            public void mouseEntered(MouseEvent e){
            public void mouseExited(MouseEvent e){
    }JApplet Class, this is what I plugged the GUI into after I made the change from Application to JApplet.
    public class AppletTest extends JApplet{
        public void init() { 
            System.out.println("Creating GUI");
            AppletGUI theGUI = new AppletGUI();
            theGUI.setVisible(true);
            Container content = getContentPane();
            content.setBackground(Color.white);
            content.setLayout(new FlowLayout());
            content.add(theGUI);
            AppletGUI theGUI = new AppletGUI();
            theGUI.setVisible(true);
            setContentPane(theGUI);
            System.out.println("GUI Displayed");
        public static void main(String[] args){
            AppletTest at = new AppletTest();
            at.init();
            at.start();
    }The CSS Generator Class. This exists because once I have the basic program working I intend to expand upon it and add multiple tabs to the GUI, each one allowing the user to change different style options. Each style option to be changed will be changed wit ha different method in this class.
    public class CSSGenerator {
        //Variables
        String background = "";
        ArrayList<String> backgroundCSS;
        //Flags
        boolean backgroundChanged = false;
        //Sets and Gets
        //For Variables
        public void setBackground(String theBackground){
            background = theBackground;
        public String getBackground(){
            return background;
        //For Flags
        public void setBackgroundChanged(boolean isBackgroundChanged){
            backgroundChanged = isBackgroundChanged;
        public boolean getBackgroundChanged(){
            return backgroundChanged;
        //background generator
        public ArrayList<String> backgroundGenerator(String backgroundURL){
            //get the URL for the background
            backgroundURL = background;
            //creat a new array list of strings
            ArrayList<String> backgroundCSS = new ArrayList<String>();
            //add the strings for the background options to the array list
            backgroundCSS.add("body");
            backgroundCSS.add("{");
            backgroundCSS.add("background-image: url(" + backgroundURL + ");");
            backgroundCSS.add("background-color: #ff0000");
            backgroundCSS.add("}");
            return backgroundCSS;
        //Write CSS to File
        public void outputCSSFile(){
            try{
                //Create CSS file
                System.out.print("creating file");
                FileWriter cssWriter = new FileWriter("C:/Documents and Settings/Gwilym/My Documents/Applet Data/CustomStyle.css");
                System.out.print("file created");
                System.out.print("creating buffered writer");
                BufferedWriter out = new BufferedWriter(cssWriter);
                System.out.print("buffered writer created");
                //check which settings have been changed
                //check background flag
                if(getBackgroundChanged() == true){
                    System.out.print("retrieving arraylist");
                    ArrayList<String> tempBGOptions = backgroundGenerator(getBackground());
                    System.out.print("arraylist retrieved");
                    int j = tempBGOptions.size();
                    for(int i = 0; i < j ; i++){
                        System.out.print("writing to the file");
                        out.write(tempBGOptions.get(i));
                        out.newLine();
                        System.out.print("written to the file");
                out.close();
            }catch (Exception e){//Catch exception if any
                System.out.println("Error: Failed to write CSS file");
        /** Creates a new instance of CSSGenerator */
        public CSSGenerator() {
    }The Backgrounds Class. This class exists because I didnt want there to just be a hardcoded lsit of backgrounds, I wanted it to be possible to add new ones to the list without simply lettign users upload their own images (since the intended users are kids and this sharepoint site is used for educational purposes, I dont want them uplaoded inapropraite backgrounds) but I do want the site admin to be able to add more images to the list. for this reason the backgrounds are taken from a list in a text file that will be stored in the same location as the applet, the file specifies the background name, where it is stored, and where a thumbnail image is stored.
    public class Backgrounds {
        //Array Lists
        private ArrayList<JPanel> backgroundsList;
        private ArrayList<String> backgroundsData;
        //Set And Get Methods
        public ArrayList getBackgroundsList(){
            return backgroundsList;
        //ArrayList Population Methods
        public void populateBackgroundsData(){
            //decalre the input streams and create a new fiel hat points to the BackgroundsData file
            File backgroundsDataFile = new File("C:/Documents and Settings/Gwilym/My Documents/Applet Data/BackgroundsData.txt");
            FileInputStream backgroundsFIS = null;
            BufferedInputStream backgroundsBIS = null;
            DataInputStream backgroundsDIS = null;
            try {
                backgroundsFIS = new FileInputStream(backgroundsDataFile);
                backgroundsBIS = new BufferedInputStream(backgroundsFIS);
                backgroundsDIS = new DataInputStream(backgroundsBIS);
                backgroundsData = new ArrayList<String>();
                String inputtedData = null;
                //loops until it reaches the end of the file
                while (backgroundsDIS.available() != 0) {
                    //reads in the data to be stored in an array list
                    inputtedData = backgroundsDIS.readLine();
                    backgroundsData.add(inputtedData);
            //TESTING
            System.out.println("\n\nTESTING: populateBackgroundsData()");
            int j = backgroundsData.size();
            for(int i = 0; i < j; i++){
                System.out.println("Index " + i + " = " + backgroundsData.get(i));
            System.out.println("\n\n");
            //close all stremas
            backgroundsFIS.close();
            backgroundsBIS.close();
            backgroundsDIS.close();
            } catch (FileNotFoundException e) {
                System.out.println("Error: File Not Found");
            } catch (IOException e) {
                System.out.println("Error: IO Exception Thrown");
        public void populateBackgroundsList(){
            backgroundsList = new ArrayList<JPanel>();
            int j = backgroundsData.size();
            System.out.println("number of backgrounds = " + j);
            backgroundsList = new ArrayList<JPanel>();
            for(int i = 0; i < j; i++){
                String tempBackgroundData = backgroundsData.get(i);
                JPanel backgroundJP = new JPanel(new GridLayout(1,2));
                JLabel backgroundNameJL = new JLabel();               
                JLabel backgroundIconJL = new JLabel();
                //split the string string and egt the background name and URL
                String[] splitBGData = tempBackgroundData.split(",");
                String backgroundName = splitBGData[0];
                String backgroundURL = splitBGData[1];
                String backgroundIcon = splitBGData[2];
                System.out.println("\nbackgroundName = " + backgroundName);
                System.out.println("\nbackgroundURL = " + backgroundURL);
                System.out.println("\nbackgroundIcon = " + backgroundIcon + "\n");
                backgroundNameJL.setText(backgroundName);
                backgroundIconJL.setIcon(new javax.swing.ImageIcon(backgroundIcon));
                backgroundJP.add(backgroundNameJL);
                backgroundJP.add(backgroundIconJL);
                backgroundJP.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
                //Name the JP as the background URL so it can be found
                //May be useful sicne the data file may need to contain 3 fields in future
                //this is incase the preview image (icon) is different from the acctual background
                //most liekly in the case of more complex ppictures rather then repeating patterns
                backgroundJP.setName(backgroundURL);
                //Add the JP to the Array List
                backgroundsList.add(backgroundJP);
            //TESTING
            System.out.println("\n\nTESTING: populateBackgroundsList()");
            j = backgroundsList.size();
            for(int i = 0; i < j; i++){
                System.out.println("Index " + i + " = " + backgroundsList.get(i));
            System.out.println("\n\n");
    }So thats my program so far, if theres anythign that needs clarifying then please jsut ask. Thank you very much for the help!

  • Problem while writing data on xls file using jxl API

    Hi,
    I am getting problem while writing data on excel file using jxl api.
    When i write data on file and all handles associated to the file are closed, file size increases but when i open the file nothing is written in it and when file is closed manually from excel window, file size decreased to its original that was before writing data.
    here is code:
              FileOutputStream os = new FileOutputStream(this.dirPath + this.fileName, true);
              WritableWorkbook this.workbook = Workbook.createWorkbook(os);
    after writing data following handler are closed:
    this.os.flush();
                        this.workbook.write();
                        this.workbook.close();
                        this.os.close();
                        this.os = null;
    can any body help me.
    Thanks in advance

    Err, I did help you. I did understand your problem; and I solved it for you. What was missing was that you apparently made no effort to understand what you were being told. Or even consider it. You just argued about it, as though you were the one with the solution, instead of the one whose code didn't work.
    And the other thing that was missing was the part where you said 'thank you' to me for solving your problem. Somewhat more appropriate than biting the hand that fed you, frankly. I do this for nothing, on my own gas, and it's extremely irritating when people keep asking about problems I have already solved for them. I am entitled to discourage that. It's part of making them more efficient actually.
    But it happens often enough that it also makes me think I'm just wasting my time. Probably I am.

Maybe you are looking for

  • How do I include the quiz taker's name in the Quiz Results email?

    I'm using Adobe Captivate 4. I want to include the quiz taker's name in the Quiz Results email. Is there to do this?

  • Multilevel Categorization

    Hello, I'm looking for a solution to have two categorization blocks in one service order. First categorization is used for internal categorization, captured by service admin. Second categorization is used to store an external categorization, captured

  • SALES TAX

    Hello I hav e abig problem because in the company I work for is located in Cameroon. I use the french localization. They have VAT but alos another tax. This tax is based on the fiscal level of the customer. As teh VAT this tax is base don Total witho

  • USB Flash Drive not mounting

    I recently bought an 8GB USB flash drive, which came formatted FAT-32. The drive was put into a friend's Windoze laptop and had a couple GBs of jpeg and avi files transferred to it. I took the drive home and put it in my white MacBook (4GB RAM, Leopa

  • Keynote: Change .kth to .key

    Hello A friend of mine saved a file in Keynote as a Template .kth. If I open it as a template, it is a clean file without text. How is it possible to open and save it as a normal .key-file? Changing the ending doesn't work.