Problem about writing txt file and  utl_put_line

After some research on the internet I found the way how to writre files from Oracle 11g to a txt file.
I read that utl_put_line only holds 32k per line and adds a new line at the end of each row but my problem it´s that if I want to open the file with SQL Server :D it doesn't recognize the CRLF so there is no end line and the last column has the data from the next row. The files are created on Linux so if I open them on Windows i have to convert into DOS format but if I try to open that file with Excel everything works fine, so I was wondering if there is a limit of columns or number of characters that can be on a txt file.
There is my pl sql that I used to create my txt files:
-------------------CODE-----------------------------
declare
cursor r1 is
select * from dqstage.st_nomdetalle
where sistema = 'NOR'
and procesar = 0
and identidad=02;
cursor r2 ( p_parid number) is
select * from dqstage.st_nomsubdetalle
where par_id = p_parid
and procesar = 0
and sistema = 'NOR'
and substr(nombrearchivo,6,2)=02;
vcadena varchar2(4000);
--vcadena1 varchar2(4000);
vcadena1 clob;
vcadena2 long;
c number:=0;
vencabezados long;
archivo sys.utl_file.file_type;
begin
archivo:= SYS.UTL_FILE.FOPEN(location=>'UPEPE_DIR',filename=>'nor02.txt',open_mode=>'w',max_linesize=>32767);
vencabezados :='FILEID|NOMBREARCHIVO|TIPOREGISTRO|IDENTIFICADORREGISTRO|FECHAEMISIONPAGO|CLAVETIPONOMINA|CLAVECT|TURNOCT|RFC|CURP|NUMEMPLEADOESTATAL'
||'|NUMSEGURIDADSOCIAL|NOMBRECOMPLETO|NOMBRES|PRIMERAPELLIDO|SEGUNDOAPELLIDO|CODIGOPAGADURIA|IDORIGENPRESUPUESTALPLAZA|CLAVEPRESUPUESTAL|'
||'PARTIDAPRESUPUESTAL|CODIGOPAGO|CLAVEUNIDAD|CLAVESUBUNIDAD|CLAVECATEGORIA|HSM|NUMEROPLAZA|CLAVENIVELPUESTO|CLAVENIVELSUELDO|ZONAECONOMICA|'
||'PERCEPCIONNETA|CLABECUENTA|NUMEROCHEQUE|CLAVEMOTIVOPAGORETROACTIVO|NUMTOTALPERDED|ERRORES|'
||'TIPOCONCEPTO1|CONCEPTOPAGO1|MONTO1|PERIODODEL1|PERIODOAL1|FUENTEFINANCIAMIENTO1|ORIGEN1|ERRORES1|'
||'TIPOCONCEPTO2|CONCEPTOPAGO2|MONTO2|PERIODODEL2|PERIODOAL2|FUENTEFINANCIAMIENTO2|ORIGEN2|ERRORES2|'
||'TIPOCONCEPTO3|CONCEPTOPAGO3|MONTO3|PERIODODEL3|PERIODOAL3|FUENTEFINANCIAMIENTO3|ORIGEN3|ERRORES3|'
||'TIPOCONCEPTO4|CONCEPTOPAGO4|MONTO4|PERIODODEL4|PERIODOAL4|FUENTEFINANCIAMIENTO4|ORIGEN4|ERRORES4|'
||'TIPOCONCEPTO5|CONCEPTOPAGO5|MONTO5|PERIODODEL5|PERIODOAL5|FUENTEFINANCIAMIENTO5|ORIGEN5|ERRORES5|'
||'TIPOCONCEPTO6|CONCEPTOPAGO6|MONTO6|PERIODODEL6|PERIODOAL6|FUENTEFINANCIAMIENTO6|ORIGEN6|ERRORES6|'
||'TIPOCONCEPTO7|CONCEPTOPAGO7|MONTO7|PERIODODEL7|PERIODOAL7|FUENTEFINANCIAMIENTO7|ORIGEN7|ERRORES7|'
||'TIPOCONCEPTO8|CONCEPTOPAGO8|MONTO8|PERIODODEL8|PERIODOAL8|FUENTEFINANCIAMIENTO8|ORIGEN8|ERRORES8|'
||'TIPOCONCEPTO9|CONCEPTOPAGO9|MONTO9|PERIODODEL9|PERIODOAL9|FUENTEFINANCIAMIENTO9|ORIGEN9|ERRORES9|'
||'TIPOCONCEPTO10|CONCEPTOPAGO10|MONTO10|PERIODODEL10|PERIODOAL10|FUENTEFINANCIAMIENTO10|ORIGEN10|ERRORES10|'
||'TIPOCONCEPTO11|CONCEPTOPAGO11|MONTO11|PERIODODEL11|PERIODOAL11|FUENTEFINANCIAMIENTO11|ORIGEN11|ERRORES11|'
||'TIPOCONCEPTO12|CONCEPTOPAGO12|MONTO12|PERIODODEL12|PERIODOAL12|FUENTEFINANCIAMIENTO12|ORIGEN12|ERRORES12|'
||'TIPOCONCEPTO13|CONCEPTOPAGO13|MONTO13|PERIODODEL13|PERIODOAL13|FUENTEFINANCIAMIENTO13|ORIGEN13|ERRORES13|'
||'TIPOCONCEPTO14|CONCEPTOPAGO14|MONTO14|PERIODODEL14|PERIODOAL14|FUENTEFINANCIAMIENTO14|ORIGEN14|ERRORES14|'
||'TIPOCONCEPTO15|CONCEPTOPAGO15|MONTO15|PERIODODEL15|PERIODOAL15|FUENTEFINANCIAMIENTO15|ORIGEN15|ERRORES15|'
||'TIPOCONCEPTO16|CONCEPTOPAGO16|MONTO16|PERIODODEL16|PERIODOAL16|FUENTEFINANCIAMIENTO16|ORIGEN16|ERRORES16|'
||'TIPOCONCEPTO17|CONCEPTOPAGO17|MONTO17|PERIODODEL17|PERIODOAL17|FUENTEFINANCIAMIENTO17|ORIGEN17|ERRORES17|'
||'TIPOCONCEPTO18|CONCEPTOPAGO18|MONTO18|PERIODODEL18|PERIODOAL18|FUENTEFINANCIAMIENTO18|ORIGEN18|ERRORES18|'
||'TIPOCONCEPTO19|CONCEPTOPAGO19|MONTO19|PERIODODEL19|PERIODOAL19|FUENTEFINANCIAMIENTO19|ORIGEN19|ERRORES19|'
||'TIPOCONCEPTO20|CONCEPTOPAGO20|MONTO20|PERIODODEL20|PERIODOAL20|FUENTEFINANCIAMIENTO20|ORIGEN20|ERRORES20|'
||'TIPOCONCEPTO21|CONCEPTOPAGO21|MONTO21|PERIODODEL21|PERIODOAL21|FUENTEFINANCIAMIENTO21|ORIGEN21|ERRORES21|'
||'TIPOCONCEPTO22|CONCEPTOPAGO22|MONTO22|PERIODODEL22|PERIODOAL22|FUENTEFINANCIAMIENTO22|ORIGEN22|ERRORES22|'
||'TIPOCONCEPTO23|CONCEPTOPAGO23|MONTO23|PERIODODEL23|PERIODOAL23|FUENTEFINANCIAMIENTO23|ORIGEN23|ERRORES23|'
||'TIPOCONCEPTO24|CONCEPTOPAGO24|MONTO24|PERIODODEL24|PERIODOAL24|FUENTEFINANCIAMIENTO24|ORIGEN24|ERRORES24|'
||'TIPOCONCEPTO25|CONCEPTOPAGO25|MONTO25|PERIODODEL25|PERIODOAL25|FUENTEFINANCIAMIENTO25|ORIGEN25|ERRORES25|'
||'TIPOCONCEPTO26|CONCEPTOPAGO26|MONTO26|PERIODODEL26|PERIODOAL26|FUENTEFINANCIAMIENTO26|ORIGEN26|ERRORES26|'
||'TIPOCONCEPTO27|CONCEPTOPAGO27|MONTO27|PERIODODEL27|PERIODOAL27|FUENTEFINANCIAMIENTO27|ORIGEN27|ERRORES27|'
||'TIPOCONCEPTO28|CONCEPTOPAGO28|MONTO28|PERIODODEL28|PERIODOAL28|FUENTEFINANCIAMIENTO28|ORIGEN28|ERRORES28|'
||'TIPOCONCEPTO29|CONCEPTOPAGO29|MONTO29|PERIODODEL29|PERIODOAL29|FUENTEFINANCIAMIENTO29|ORIGEN29|ERRORES29|'
||'TIPOCONCEPTO30|CONCEPTOPAGO30|MONTO30|PERIODODEL30|PERIODOAL30|FUENTEFINANCIAMIENTO30|ORIGEN30|ERRORES30|'
||'TIPOCONCEPTO31|CONCEPTOPAGO31|MONTO31|PERIODODEL31|PERIODOAL31|FUENTEFINANCIAMIENTO31|ORIGEN31|ERRORES31|'
||'TIPOCONCEPTO32|CONCEPTOPAGO32|MONTO32|PERIODODEL32|PERIODOAL32|FUENTEFINANCIAMIENTO32|ORIGEN32|ERRORES32|'
||'TIPOCONCEPTO33|CONCEPTOPAGO33|MONTO33|PERIODODEL33|PERIODOAL33|FUENTEFINANCIAMIENTO33|ORIGEN33|ERRORES33|'
||'TIPOCONCEPTO34|CONCEPTOPAGO34|MONTO34|PERIODODEL34|PERIODOAL34|FUENTEFINANCIAMIENTO34|ORIGEN34|ERRORES34|'
||'TIPOCONCEPTO35|CONCEPTOPAGO35|MONTO35|PERIODODEL35|PERIODOAL35|FUENTEFINANCIAMIENTO35|ORIGEN35|ERRORES35|'
||'TIPOCONCEPTO36|CONCEPTOPAGO36|MONTO36|PERIODODEL36|PERIODOAL36|FUENTEFINANCIAMIENTO36|ORIGEN36|ERRORES36|'
||'TIPOCONCEPTO37|CONCEPTOPAGO37|MONTO37|PERIODODEL37|PERIODOAL37|FUENTEFINANCIAMIENTO37|ORIGEN37|ERRORES37|'
||'TIPOCONCEPTO38|CONCEPTOPAGO38|MONTO38|PERIODODEL38|PERIODOAL38|FUENTEFINANCIAMIENTO38|ORIGEN38|ERRORES38|'
||'TIPOCONCEPTO39|CONCEPTOPAGO39|MONTO39|PERIODODEL39|PERIODOAL39|FUENTEFINANCIAMIENTO39|ORIGEN39|ERRORES39|'
||'TIPOCONCEPTO40|CONCEPTOPAGO40|MONTO40|PERIODODEL40|PERIODOAL40|FUENTEFINANCIAMIENTO40|ORIGEN40|ERRORES40|'
||'TIPOCONCEPTO41|CONCEPTOPAGO41|MONTO41|PERIODODEL41|PERIODOAL41|FUENTEFINANCIAMIENTO41|ORIGEN41|ERRORES41|'
||'TIPOCONCEPTO42|CONCEPTOPAGO42|MONTO42|PERIODODEL42|PERIODOAL42|FUENTEFINANCIAMIENTO42|ORIGEN42|ERRORES42|'
||'TIPOCONCEPTO43|CONCEPTOPAGO43|MONTO43|PERIODODEL43|PERIODOAL43|FUENTEFINANCIAMIENTO43|ORIGEN43|ERRORES43|'
||'TIPOCONCEPTO44|CONCEPTOPAGO44|MONTO44|PERIODODEL44|PERIODOAL44|FUENTEFINANCIAMIENTO44|ORIGEN44|ERRORES44|'
||'TIPOCONCEPTO45|CONCEPTOPAGO45|MONTO45|PERIODODEL45|PERIODOAL45|FUENTEFINANCIAMIENTO45|ORIGEN45|ERRORES45|'
||'TIPOCONCEPTO46|CONCEPTOPAGO46|MONTO46|PERIODODEL46|PERIODOAL46|FUENTEFINANCIAMIENTO46|ORIGEN46|ERRORES46|'
||'TIPOCONCEPTO47|CONCEPTOPAGO47|MONTO47|PERIODODEL47|PERIODOAL47|FUENTEFINANCIAMIENTO47|ORIGEN47|ERRORES47|'
||'TIPOCONCEPTO48|CONCEPTOPAGO48|MONTO48|PERIODODEL48|PERIODOAL48|FUENTEFINANCIAMIENTO48|ORIGEN48|ERRORES48|'
||'TIPOCONCEPTO49|CONCEPTOPAGO49|MONTO49|PERIODODEL49|PERIODOAL49|FUENTEFINANCIAMIENTO49|ORIGEN49|ERRORES49|'
||'TIPOCONCEPTO50|CONCEPTOPAGO50|MONTO50|PERIODODEL50|PERIODOAL50|FUENTEFINANCIAMIENTO50|ORIGEN50|ERRORES50';
--||'TIPOCONCEPTO51|CONCEPTOPAGO51|MONTO51|PERIODODEL51|PERIODOAL51|FUENTEFINANCIAMIENTO51|ORIGEN51|ERRORES51';
sys.utl_file.put_line(archivo, vencabezados);
for i in r1 loop
c:=c+1;
vcadena := i.fileid||'|'||i.nombrearchivo||'|'||i.tiporegistro||'|'||i.identificadorregistro||'|'||i.fechaemisionpago||'|'||i.clavetiponomina||'|'||i.clavect||'|'||i.turnoct||'|'||i.rfc
||'|'||i.curp||'|'||i.numempleadoestatal||'|'||i.numseguridadsocial||'|'||i.nombrecompleto||'|'||i.nombres||'|'||i.primerapellido||'|'||i.segundoapellido||'|'||i.codigopagaduria
||'|'||i.idorigenpresupuestalplaza||'|'||i.clavepresupuestal||'|'||i.partidapresupuestal||'|'||i.codigopago||'|'||i.claveunidad||'|'||i.clavesubunidad||'|'||i.clavecategoria||'|'||i.hsm
||'|'||i.numeroplaza||'|'||i.clavenivelpuesto||'|'||i.clavenivelsueldo||'|'||i.zonaeconomica||'|'||i.percepcionneta||'|'||i.clabecuenta||'|'||i.numerocheque||'|'||i.clavemotivopagoretroactivo
||'|'||i.numtotalperded||'|'||i.errores;
vcadena1:=null;
for j in r2 (i.fileid) loop
vcadena1 := vcadena1||'|'|| j.tipoconcepto||'|'||j.conceptopago||'|'||j.monto||'|'||j.periododel||'|'||j.periodoal||'|'||j.fuentefinanciamiento ||'|'||j.origen||'|'||j.errores;
end loop;
sys.utl_file.put_line(archivo, vcadena2);
end loop;
sys.utl_file.fclose(archivo);
end;
As you can see I write the column names first and with a loop I add the data, so I can have a very large column at the end.
How can I add the CRLF at the end of each line to have it working with Windows?

user2068122 wrote:
After some research on the internet I found the way how to writre files from Oracle 11g to a txt file.
I read that utl_put_line only holds 32k per line and adds a new line at the end of each row but my problem it´s that if I want to open the file with SQL Server :D it doesn't recognize the CRLF so there is no end line and the last column has the data from the next row. The files are created on Linux so if I open them on Windows i have to convert into DOS format but if I try to open that file with Excel everything works fine, so I was wondering if there is a limit of columns or number of characters that can be on a txt file.
<snip>
Oracle is simply passing a string of characters to the OS to be written to a file in the host OS's native text format. That format is different from Windows and nix.  Windows will append a CR-LF pair to the end of the provided character string, as its end-of-record delimiter.  nix will append only a CR (or is it LF?) as its end-of-record delimiter. This is purely and OS issue that Oracle knows or cares nothing about. It is also something that must always be kept in mind when passing files between *nix and Windows.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • 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!

  • Reading .txt files and put it into a TextArea

    Hi all,
    I got a problem! I have to make something like a messenger.
    I want to put the written text into a .txt file, after that I have to get the text out of the .txt file and put in into a TextArea.
    I would ike it to to that like this:
    ">User 1
    Hello!
    >User 2
    Hi!
    Now here are my questions:
    1: What is the moet easy way to do this ?
    2: How could i put Enters into a .txt file with Java ?
    3: How could i read all the text from the .txt file and put it into a TextArea WITH ENTERS ?
    Thanks for your help!
    Greetings, Jasper Kouwenberg

    use JTextArea.read(new FileReader(fileName)) for reading.
    and JTextArea.write(new FileWriter(fileName)) for writing.
    The enters should be ok if the user press enter and adds a new line ("\n") to the text area component.
    It will save the enter in the text file and load it correctly back to the text area.
    If you want to add enter programmatically just add "\n" string to the text area component.

  • I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?

    I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
    Attachments:
    try2.txt ‏2 KB
    read_array.vi ‏21 KB

    The problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
    Here are some of your choices to fix your problem.
    1. Change the source file to a tab delimited file. Your VI will then run as is.
    2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
    3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
    Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
    Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does.

  • How to encypt a .txt file and how to decrypt a same .txt file when i need

    My requirement is i want to encrypt a .txt file and
    keep it in some folder. In that file we put database connection
    information. when ever we need that file we have to access it and decrypt
    it. with that decrypted values we have make connection with database.
    i am sending a code in which i wrote both encyption and decrytion in same file, but i want to do it separately.
    Please help me regarding this.
    package com.businessobjects;
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    public class EncryptDecrypt
         public static void EncodeIt()
              try
              // generate Cipher objects for encoding and decoding
              Cipher itsocipher1 = Cipher.getInstance("DES");
              Cipher itsocipher2 = Cipher.getInstance("DES");
              // generate a KeyGenerator object
              KeyGenerator KG = KeyGenerator.getInstance("DES");
              System.out.println("Using algorithm " + KG.getAlgorithm());
              // generate a DES key
              Key mykey = KG.generateKey();
              // initialize the Cipher objects
              System.out.println("Initializing ciphers...");
              itsocipher1.init(Cipher.ENCRYPT_MODE, mykey);
              itsocipher2.init(Cipher.DECRYPT_MODE, mykey);
              // creating the encrypting cipher stream
              //System.out.println("Creating the encrypting cipher stream...");
              /*FileInputStream fis = new FileInputStream("Original.txt");
    FileOutputStream fos = new FileOutputStream("Encypt.txt");
              CipherInputStream cis1 = new CipherInputStream(fis, itsocipher1);
              // creating the decrypting cipher stream
              //System.out.println("Creating the decrypting cipher stream...");
              byte[] b1 = new byte[8];
    int i1 = cis1.read(b1);
              while (i1 != -1)
                   fos.write(b1, 0, i1);
                   i1 = cis1.read(b1);
    fis.close();
    fos.close();*/
    // writing the decrypted data to output file
    FileInputStream fis1 = new FileInputStream("Encypt.txt");
    FileOutputStream fos1 = new FileOutputStream(Decypt.txt");
    CipherInputStream cis2 = new CipherInputStream(fis1, itsocipher2);
              byte[] b2 = new byte[8];
              int i2 = cis2.read(b2);
              while (i2 != -1)
                   fos1.write(b2, 0, i2);
                   i2 = cis2.read(b2);
    fis1.close();
              fos1.close();
    //cis1.close();
              cis2.close();
              catch (Exception e)
              System.out.println("Caught exception: " + e);
    With regards
    Pavankumar.

    here is the solution you wanted it
    uses password based encryption
    but your requirements are for very badly
    designed code
    This is the encryption part
    it converts the inputfile original.txt
    into the outputfile encrypt.txt which
    contains the original encrypted
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import javax.crypto.Cipher;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    public class PWBEncryption {
        // Salt
        static byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        // Iteration count
        static int count = 20;
        public PWBEncryption() {
        // params:
        // password   -> the pasword used to create the key
        // inputfile  -> the file containing the stuff to be encrypted
        // i.e. original.txt
        // outputfile -> the file that will contain the encrypted stuff
        // i.e. encrypt.txt
        public static boolean doIt(char[] password,String inputfile,String outputfile){
            try{
                // Create PBE parameter set
                PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
                PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
                // create secretkey
                SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
                SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
                // create cipher
                Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
                pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
                // read input
                FileInputStream fis = new FileInputStream(inputfile);
                byte[] input = new byte[fis.available()];
                fis.read(input);
                // encrypt
                byte[] output = pbeCipher.doFinal(input);
                // write encrypted output
                FileOutputStream fos = new FileOutputStream(outputfile);
                fos.write(output);
                return true;
            catch(Exception e){
                System.out.println(e.toString());
                return false;
    }This is the decrypt part
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import javax.crypto.Cipher;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    public class PWBDecryption {
        // Salt
        static byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        // Iteration count
        static int count = 20;
        public PWBDecryption() {
        // params:
        // password   -> the pasword used to create the key
        // inputfile  -> the file containing the decrypted data
        // i.e. encrypt.txt
        // outputfile -> the file that will contain the decrypted data
        // i.e. decrypt.txt
        public static boolean doIt(char[] password,String inputfile,String outputfile){
            try{
                // Create PBE parameter set
                PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
                PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
                // create secretkey
                SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
                SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
                // create cipher
                Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
                pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
                // read input
                FileInputStream fis = new FileInputStream(inputfile);
                byte[] input = new byte[fis.available()];
                fis.read(input);
                // encrypt
                byte[] output = pbeCipher.doFinal(input);
                // write encrypted output
                FileOutputStream fos = new FileOutputStream(outputfile);
                fos.write(output);
                return true;
            catch(Exception e){
                return false;
    }runner
    public class RunRun {
        public RunRun() {
        public static void main(String args[]){
            char password[] = {'q','w','e','r','t','y'};       
            boolean enc = PWBEncryption.doIt(password,"C:\\original.txt","c:\\encrypt.txt");
            System.out.println("Encryption status == "+enc);
            boolean dec = PWBDecryption.doIt(password,"c:\\encrypt.txt","c:\\decrypt.txt");
            System.out.println("Decryption status == "+dec);
    }

  • I have dragged 2 files to the trash bin but I cannot delete them from the trash bin. It keeps telling me these files are in use when they are not. How do I delete these files? One is a txt file and the other is an xls file

    I have dragged 2 files to the trash bin but I cannot delete them from the trash bin. It keeps telling me these files are in use when they are not. How do I delete these files? One is a txt file and the other is an xls file

    From the Finder menu select 'Secure Empty Trash'. If this or the suggestion above doesn't resolve the problem take a look at the various suggestions in this link:
    http://www.thexlab.com/faqs/trash.html

  • Problem with printing txt file

    I have a problem with printing txt file. My code looks like :
    String filename = something.txt";
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(
              flavor, null);
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    pras.add(PrintQuality.DRAFT);
    pras.add(new Copies(1));
    pras.add(MediaSizeName.ISO_A4);
    pras.add(Sides.ONE_SIDED);
    pras.add(Chromaticity.MONOCHROME);
    PrintService service = ServiceUI.printDialog(null, 200, 200,
              services, services[0],
              null,
              pras);
    if (service != null)
    try
    DocPrintJob job = service.createPrintJob();
    FileInputStream fis = new FileInputStream(filename);
    DocAttributeSet das = new HashDocAttributeSet();
    Doc doc = new SimpleDoc(fis, flavor, das);
    job.print(doc, pras);
    Thread.sleep(10000);
    catch(FileNotFoundException e)
    catch(PrintException e1)
    catch(InterruptedException e2)
    It doesn't work :(
    What is my purpose: I would like to print .txt file but I would like to get PrintDialog where I can choose PrintQuality, Chromaticity etc. I found also that I should use DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST but I don't know how.
    I will be very gratefull for help :)

    I tested it on 3 printers (different models of hp). 2 of them don't give me any error but when it started print priter stoped (just as it dosesn't have a paper), but 1 of them doesn't react (there were no errors), i thought tahat something was wrong with printers but when I change DocFlavor.INPUT_STREAM.AUTOSENSE to DocFlavor.GIF and filename to dog.gif it works so mybe there is another way to print txt file

  • Adding line to txt file and then rename

    Hello there. I am trying to create a class that will add a line to a txt file and then if the nuber of lines are greater than 5 it will rename the file.
    I think I have solved it with this class.
    My problem is that the file2.renameTo does not work does anyone have any suggestions why?
             public void CopyLines(String string, String location, String fileName) throws IOException {
                 BufferedReader inputStream = null;
                 PrintWriter outputStream = null;
                   GregorianCalendar calendar = new GregorianCalendar(Locale.UK);
                boolean b=false;
                 try {
                     int counter = 0;
                      File file2 = new File(location + fileName);
                      ArrayList arrays = new ArrayList();
                      if (file2.exists()){
                     inputStream =
                         new BufferedReader(new FileReader(file2));
                     String l;
                     while ((l = inputStream.readLine()) != null) {
                          arrays.add(l);
                         counter++;
                     outputStream =
                         new PrintWriter(new FileWriter(location + fileName));
                      if (!arrays.isEmpty()){
                           for(int i= 0; i<arrays.size();i++){
                              outputStream.println(arrays.get(i));
                     outputStream.println(string);
                     if (counter>5){
                          String newFileName = location + fileName + calendar.getTime().getTime();
                          b = file2.renameTo(new File(newFileName));
                 } finally {
                     if (inputStream != null) {
                         inputStream.close();
                     if (outputStream != null) {
                         outputStream.close();
             }

    What is ". . .does not work. . ."?

  • Scenario to read from txt-file and create a sales order

    Hi,
    i have started creating a scenario to read from an txt-file and to create a sales order.
    When i activate my scenario, i get the following message :
        no scenario step (vBIU) associated for this step for the incoming system (SysId)
    When i look into the detailed xml-file i see that all the records are read from the file, but there is no next step to be treated.
    Has somebody any idea how this come ?
    -<Msg MessageLog="true" msglogexcl="false" logmsg="0009" recording="true" BeginTimeStamp="20111202095144" MessageId="11120209514499820828C0A801674F24" xmlns="urn:com.sap.b1i.vplatform:entity">-<Header><msglog b1ifactive="true" always="false" step="Default message log"/>-<Resumption><starter ipo="/vP.0010000138.in_FEAN/com.sap.b1i.vplatform.runtime/INB_FI_EXST_ASYN_NAM/INB_FI_EXST_ASYN_NAM.ipo/proc"/></Resumption><IPO tid="11120205535899820808C0A801678C54" Id="INB_FI_EXST_ASYN_NAM"/><Sender Id="0010000138"/><Inbound file="ORDERS_TEST" ext="csv" path="C:\TEMP\In" pltype="txt" wrap="" deli=";"/></Header>-<Body><Payload Type="File exist" Role="T"/>-<Payload Role="S">-<io xmlns="urn:com.sap.b1i.bizprocessor:bizatoms" pltype="txt">
    -<row>
    <col>OH</col>
    <col>0000087077</col>
    <col>201110041205</col>
    <col>220</col>
    <col>9</col>
    <col>201110191702</col>
    <col>8710624300012</col>
    <col>8714252008609</col>
    <col>8710624300012</col>
    <col>8714252008609</col>
    <col>8710624300012</col>
    <col>N</col>
    <col>N</col>
    <col>N</col>
    </row>
    -<row>
    <col>OL</col>
    <col>1</col>
    <col>8711715844378</col>
    <col>20</col>
    </row>-<row>
    <col>OL</col>
    <col>2</col>
    <col>8711715844392</col>
    <col>60</col>
    </rowrow>
    <col>OL</col>
    <col>16</col>
    <col>8710251791092</col>
    <col>280</col>
    </row>
    </io>
    </Payload>
    </Body>
    </Msg>
    This is my final atom :
    <?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet xmlns:b1e="urn:com.sap.b1i.sim:b1event" xmlns:b1ie="urn:com.sap.b1i.sim:b1ievent" xmlns:bfa="urn:com.sap.b1i.bizprocessor:bizatoms" xmlns:jdbc="urn:com.sap.b1i.adapter:jdbcadapter" xmlns:rfc="urn:sap-com:document:sap:rfc:functions" xmlns:sim="urn:com.sap.b1i.sim:entity" xmlns:utils2="com.sap.b1i.bpc_tools.Utilities" xmlns:vpf="urn:com.sap.b1i.vplatform:entity" xmlns:xci="urn:com.sap.b1i.xcellerator:intdoc" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" bfa:force="" vpf:force="" jdbc:force="" rfc:force="" b1ie:force="" b1e:force="" xci:force="" sim:force="" utils2:force=""><xsl:output method="xml" encoding="UTF-8" indent="yes"></xsl:output><xsl:param name="atom"></xsl:param><xsl:param name="sessionid"></xsl:param><xsl:variable name="msg" select="/vpf:Msg/vpf:Body/vpf:Payload[./@Role=&apos;S&apos;]"></xsl:variable><xsl:variable name="vpSender" select="/vpf:Msg/vpf:Header/vpf:Sender/@Id"></xsl:variable><xsl:variable name="vpObject" select="/vpf:Msg/vpf:Header/vpf:Sender/@ObjId"></xsl:variable><xsl:variable name="vpReceiver" select="/vpf:Msg/vpf:Header/vpf:ReceiverList/vpf:Receiver[./@handover=&apos;P&apos;]/@Id"></xsl:variable><xsl:template match="/">
    <Msg xmlns="urn:com.sap.b1i.vplatform:entity">
    <xsl:copy-of select="/vpf:Msg/@*"></xsl:copy-of>
    <xsl:copy-of select="/vpf:Msg/vpf:Header"></xsl:copy-of>
    <Body>
    <xsl:copy-of select="/vpf:Msg/vpf:Body/*"></xsl:copy-of>
    <Payload Role="R" id="{$atom}">
    <xsl:call-template name="transform"></xsl:call-template>
    </Payload>
    </Body>
    </Msg>
    </xsl:template><xsl:template name="transform">
    <FinalAtomResult xmlns="">
    <BOM>
    <BO>
    <AdmInfo>
    <Object>17</Object>
    <Version>2</Version>
    </AdmInfo>
         <Documents>
         <row>
         <DocDate>
              <xsl:copy-of select="$msg/io/row[0]/col[2]/text()"></xsl:copy-of>
         </DocDate>
         <DocDueDate>
              <xsl:copy-of select="$msg/io/row[0]/col[5]/text()"></xsl:copy-of>
         </DocDueDate>
         <CardCode>KD10251</CardCode>
         <NumAtCard>
              <xsl:copy-of select="$msg/io/row[0]/col[1]/text()"></xsl:copy-of>
         </NumAtCard>
         <U_PMX_JD_COMP>32</U_PMX_JD_COMP>
         </row>
                          </Documents>
         <Document_Lines>
         <xsl:for-each select="$msg/io/row">
         <row>
         <BarCode>
              <xsl:copy-of select="$msg/io/row[*]/col[2]/text()"></xsl:copy-of>
         </BarCode>
         <Quantity>
              <xsl:copy-of select="$msg/io/row[*]/col[3]/text()"></xsl:copy-of>
         </Quantity>
         </row>
         </xsl:for-each>
         </Document_Lines>

    Mike,
    you were right, you may not specify the extension of a file.
    Another thing i detected is that the loop of my data start with the index 1 instead of 0 !!!
    In this scenario, i have to read all the lines of the file and each time i should do a SQL-query,
    so that i can use the result to build my sales document.
    Do you know if it this is possible or have you any idea how to do this ?
    thx,
    Mario

  • How to search a special string in txt file and return it's position in txt file?

    How to search a special string in txt file and return it's position in txt file?

    I just posted a solution for a similar question here:  http://forums.ni.com/ni/board/message?board.id=170​&view=by_date_ascending&message.id=362699#M362699
    The top portion can search for the location of a string, while the bottom portion is to locate the position of a character.  Both can search for a character.
    The position of the character within the file is displayed in the indicator(s).
    R

  • How can i open a DOC or TXT file and insert the data into table?

    How can i open a DOC or TXT file and insert the data into table?
    I have a doc file . the doc include some columns and some rows.(for example 'ID,Name,Date,...').
    I'd like open DOC file and I'd like insert them into the table with same columns.
    Thanks.

    Use the SQL*Loader utility or the UTL_FILE package.

  • Every time I try to download the new version of Adobe Flash Player it saves as a .txt file and I do not know how to get it to save in the correct format.

    Every time I try to download the new version of Adobe Flash Player it saves as a .txt file and I do not know how to get it to save in the correct format.

    Please post in the Adobe Flash Player forum.

  • Reading integers from a .txt file and computing means

    I have a program that uses for loops to produce ten integers (1-10) are returns the average mean, geometric mean, and harmonic mean.
    Now i need to change this program to read integers from a .txt file and return the same data. Basically i need to change my for statements that are incrementing to read the text file.
    Thanks guys.

    You haven't asked a question. You haven't posted code. What are you expecting here?
    But I guess I'll take a stab at it and say you should look at the Scanner class
    http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
    or BufferedReader
    http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html
    I'll never understand what makes people come to the forums, create an account, and ask a lazy question, when they could get a great answer much quicker through Google.
    http://www.google.com/search?q=java+file+input (hint: look at the second search result)

  • Reading from a txt file and storing into a list

    i want to read a list of counters(String) which are there in a flat txt file and store them into a List.
    Any suggestion will be helpful
    sanjeev

    Try this
    try {
              FileReader fr = new FileReader("C:/abc.txt");
              BufferedReader br = new BufferedReader(fr);
              String record = null;
              while ((record = br.readLine()) != null)
                   System.out.println(record );     
              

Maybe you are looking for

  • I accidentally formatted my portable hard drive when setting it up for time machine. Is there any way for me to get back my lost files?

    I have an external hard drive of the brand Western Digital. Before I got my iMac I moved a lot of my important files from my PC to the hard drive and today I went on and connected it to my iMac to move my files over to it. When it had connected a win

  • New battery is not working on Satellite C855-29N

    I purchased a battery. I've put it in to the laptop and the battery light is just flashing orange. I tried removing the ac adaptor and battery and holding down the power butter for 30-40 seconds before putting the new battery back in again, plugging

  • Can't Open My AppleWorks Document!!!

    I created an apple works word document, and I had prevously saved it. After I spell checked it, it wouldn't let me save. I figured that I would just close it, then open it again, and see if that would do anything. When I went to open it again, it wou

  • Copy .git directories keeping the directory structure

    I want to create a script that searches through all folders in one drive and copy all folder named .git and it's content on a backup location with the exact same folder sturcture. For example: take this structure root | + Folder 1 + .git | | Folder 1

  • CS4 Audio echoes while capturing

    Hello, The audio sounds like an echo while I am capturing, the second voice is heard about 1 -  2 seconds later.  How can I get rid of this problem?  The recorded material does not have this problem.  Please help me get rid of the duplicate sound.  T