Reading file problem

Hi all,
I wonder wether I can go beyond my java leve. Here is a stupid problem but could not find it out where in the code ?
I want to read a file where each line will have 2 strings separated by a comma delemiter. for e.g
ABC,DEF
FDG,TYH
GHJ,ABC
my code should read the file in a loop and the first string should go to String variable concept1 and the second string should be the value of Concept2. In my code I could get the first line not beyond that and the error shows :
ABC,DEF
java.util.NoSuchElementException
     at java.util.StringTokenizer.nextToken(StringTokenizer.java:259)
     at GetNodes.main(GetNodes.java:24)
Exception in thread "main"
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
my code is :
import java.util.*;
import java.io.*;
public class GetNodes
     static StringTokenizer st;
     static String token="";
     public static void main(String [] args)throws IOException
          String concept1="";
          String concept2="";
          BufferedReader br=new BufferedReader(new FileReader("smita.txt"));
          String line;
          while((line=br.readLine())!=null)
               st=new StringTokenizer(line);
               while(st.hasMoreTokens())
                    concept1=st.nextToken();
                    System.out.println(concept1);
                    while(!concept1.equals(","))
                         token=st.nextToken();
                         concept2=token;
                         System.out.println(concept2);
                         token=st.nextToken();
//concept1=token;
               I know the code is not efficient but that is what at best I can do with my level.
Thanks and apreciate your comments
cheers

the reason you're getting this error is because you're calling your "st.nextToken() twice, if it reached the EOL then it will throw a NoSuchElementException
                    while(!concept1.equals(","))
                         token=st.nextToken();
                         concept2=token;
                         System.out.println(concept2);
                         token=st.nextToken();
               }-- you can use List to store your data from your text file, I modified your code into much simpler way like this:
import java.util.*;
import java.io.*;
public class GetNodes
     static StringTokenizer st;
     static String token="";
     public static void main(String [] args)throws IOException
     List concept=new ArrayList();
     BufferedReader br=new BufferedReader(new FileReader("smita.txt"));
     String line;
     while((line=br.readLine())!=null)
          st=new StringTokenizer(line, ",");
          while(st.hasMoreElements())
               concept.add(st.nextElement()); 
    for (int i = 0; i<concept.size(); i++)
        System.out.println (concept.get(i));
}

Similar Messages

  • Xcode writting/reading file problem

    Hi,
    im using xcode to compile in c  language, but im having problem with files, writting/reading simply doesnt work (to be exact i have to say that i copied source code to dev-c++ on windows platform to check the code and it works normaly as it should) any suggestions?
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    int main (int argc, const char * argv[])
      char tekst[]="tujesttekstktorychchcezapisacdopliku";
              char tekst2[20];
      FILE *plik;   /*r=read, w=write, rwx-obydwachyba, wb-tryb binarny*/
              if ((plik=fopen("text", "w"))==NULL)
      printf("plik nie zostal otworzony");
              fprintf(plik, "%s" ,tekst);  /*wpisanie tekstu*/
              fscanf(plik, "%s",tekst2);
      printf("tekst2: %s\n", tekst2);
              if (fclose(plik)!=0)
      printf("blad przy zamykaniu");
        printf("Hello, World!\n");
        return 0;
    the result of this program is "hello world" ONLY.
    file is clean, same thing with test2 variable.
    in copied code opening mode is "w" but ive checked almost all options ofc including binary file modes (both doesnt work)
    any suggestions?
    Message was edited by: Entwu

    while( (len = in2.read(b,0,1024)) != -1 )
    bytcount=bytcount+1024;
    inFile.write(b,0,1024);
    } This is where you go wrong ... suppose you're reading, say 100 bytes instead of the maximum 1024;
    you're still writing 1024 bytes instead of those 100 bytes; your 'bytcount' goes berzerk too. Have a
    look at this -- while( (len = in2.read(b,0,1024)) != -1 ) {
       bytcount=bytcount+len;
       inFile.write(b,0,len);
    } kind regards,
    Jos

  • Im using xcode 4.6 and im having problems reading files using the fopen function in c

    Im using xcode 4.6 and im having problems reading files using the fopen function in c

    Yes, but that would not cause the "build  failed" message.
    right I missed that part. Looks like two problems then.
    //  main.m
    //  ASCTestFopen
    //  Created by Frank Caggiano on 3/2/13.
    //  Copyright (c) 2013 Frank Caggiano. All rights reserved.
    #import <Foundation/Foundation.h>
    #include <stdio.h> 
    int main(int argc, const char * argv[])
        @autoreleasepool {
            FILE *fp, *fopen();
            // insert code here...
            if((fp = fopen("~/test.txt","r")) == NULL)
                NSLog(@"open failed");
        return 0;
    This will compile ad run in Xcode with a project type of comand line tool

  • I just stared having problems with importing files from nikon D810 into LR 5.7 it pop a window saying it can not read files on working on a imac 27" running yosemite on my mac pro after a few times it finally was able to read files and import them into LR

    I just stared having problems with importing files from nikon D810 into LR 5.7 it pop a window saying it can not read files on working on a imac 27" running yosemite on my mac pro after a few times it finally was able to read files and import them into LR I never had this problem before was there some kind of update that could of cause this?

  • Having problems extracting/convert Adobe Reader Pdf files to Adobe Digital Reader files.

    I am currently having problems trying to convert my Adobe Acrobat PDF file to and Adobe Digital Reader File.
    o

    What kind of problems?

  • Problem in reading  file

    Hi,
    Here i read file then i want to put it's contents in textarea . I used FileInputStream and bufferedInputstream for reading file but the content not appear in the textarea . why this ?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    public class FileChooserTest extends JFrame {
        private JButton button;
        private JPanel panel;
        private JFileChooser fileChooser;
        private File file = null;
        private JTextArea area;
        private FileInputStream fileInputStream = null;
        private BufferedInputStream bufferedInputStream = null;
        public FileChooserTest() {
            fileChooser = new JFileChooser();
            area = new JTextArea(50, 60);
            panel = new JPanel(new FlowLayout());
            button = new JButton("open");
            panel.add(button);
            panel.add(area);
            getContentPane().add(panel, BorderLayout.CENTER);
            fileChooser.setSelectedFile(new File(".txt"));
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int returnValue = fileChooser.showOpenDialog(FileChooserTest.this);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        file = fileChooser.getSelectedFile();
                        try {
                            fileInputStream = new FileInputStream(file);
                            bufferedInputStream = new BufferedInputStream(fileInputStream);
                            try {
                                while (bufferedInputStream.available() != 0) {
                                    area.setText(String.valueOf(bufferedInputStream.read()));
                            } catch (IOException ex) {
                                ex.printStackTrace();
                        } catch (FileNotFoundException ex) {
                            ex.printStackTrace();
        public static void main(String[] args) {
            FileChooserTest fileChooserTest = new FileChooserTest();
            fileChooserTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            fileChooserTest.setSize(new Dimension(600, 300));
            fileChooserTest.setLocationRelativeTo(null);
            fileChooserTest.setVisible(true);
    }Thanks in advance

    I changed all error in the code but also the text not appear on the textarea . why ?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    public class FileChooserTest extends JFrame {
        private JButton button;
        private JPanel panel;
        private JFileChooser fileChooser;
        private File file = null;
        private JTextArea area;
        private FileInputStream fileInputStream = null;
        private BufferedInputStream bufferedInputStream = null;
        private ByteArrayInputStream byteArrayInputStream = null;
        private byte[] bufferRead;
        public FileChooserTest() {
            fileChooser = new JFileChooser();
            area = new JTextArea(50, 60);
            panel = new JPanel(new FlowLayout());
            button = new JButton("open");
            panel.add(button);
            panel.add(area);
            getContentPane().add(panel, BorderLayout.CENTER);
            fileChooser.setSelectedFile(new File(".txt"));
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int returnValue = fileChooser.showOpenDialog(FileChooserTest.this);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        file = fileChooser.getSelectedFile();
                        int i = 0;
                        try {
                            fileInputStream = new FileInputStream(file);
                            bufferedInputStream = new BufferedInputStream(fileInputStream);
                            StringBuilder stringBuilder = new StringBuilder();
                            bufferRead = new byte[(int) file.length()];
                            try {
                                while ((i = bufferedInputStream.available()) > 0) {
                                    bufferRead[i] = new Byte((byte) i);
                                    byteArrayInputStream = new ByteArrayInputStream(bufferRead, 0, (int) file.length());
                                    stringBuilder.append(byteArrayInputStream);
                                area.setText(stringBuilder.toString());
                            } catch (IOException ex) {
                                ex.printStackTrace();
                        } catch (FileNotFoundException ex) {
                            ex.printStackTrace();
        public static void main(String[] args) {
            FileChooserTest fileChooserTest = new FileChooserTest();
            fileChooserTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            fileChooserTest.setSize(new Dimension(600, 300));
            fileChooserTest.setLocationRelativeTo(null);
            fileChooserTest.setVisible(true);
    }please help me in this . i tried but i can not .
    Thnaks
    Edited by: beshoyatefw on May 6, 2010 3:42 PM

  • Problem while reading files

    I am reading all the files which are in a particular order like file 1,file2 etc.. using a for loop but depending on the context some files may be missing and my program exits when it does not find a file with FileNot Found Exception.PLease help me with this regard as to how to continue if for example file 2 is missing then ignore and start reading file 3.
    Note the file name are same except for serila number

    with FileNot Found Exception.PLease help me with this
    regard as to how to continue if for example file 2
    is missing then ignore and start reading file 3.I assume you've basically got this design
    foreach (file : files) {
    //open the file
    //read the file
    //close the file
    //do something with the data
    }put 'try {' right below the foreach part and a ' catch (IOException ex)' above the closing }

  • Uploading and reading file from application server

    Hi
    My problem is when am uploading a file to application server it is getting stored in
    usr/sap/transyp1/prod/in   directory
    after that i want to read that file from application server to update database
    when  using below code it is showing some other directory in f4 help
    DATA: lv_hostname TYPE msxxlist-name.
    DATA: lv_server TYPE bank_dte_jc_servername.
    PARAMETERS: p_file TYPE rlgrap-filename.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
    CALL FUNCTION 'BANK_API_SYS_GET_CURR_SERVER'
    IMPORTING
    e_server = lv_server.
    lv_hostname = lv_server.
    CALL FUNCTION 'F4_DXFILENAME_4_DYNP'
    EXPORTING
    dynpfield_filename = 'P_FILE'
    dyname = sy-cprog
    dynumb = '1000'
    filetype = 'P'
    location = 'A'
    server = lv_hostname.
    experts could you please help me out
    Thanks & Regards
    Nagesh.Paruchuri

    User Transaction file. You will get all logical file path names.
    used following fucntion module to read file name and use command open dataset to read the file.
    CALL FUNCTION 'FILE_GET_NAME'
           EXPORTING
                CLIENT           = SY-MANDT
                LOGICAL_FILENAME = C_LOGICAL_FILENAME
                OPERATING_SYSTEM = SY-OPSYS
                PARAMETER_1      = P_IN_FILENAME
           IMPORTING
                FILE_NAME        = P_OUT_FILENAME
           EXCEPTIONS
                FILE_NOT_FOUND   = 1
                OTHERS           = 2.
    OPEN DATASET P_OPEN_FILE ENCODING UTF-8 IN TEXT MODE FOR OUTPUT.
      IF SY-SUBRC <> 0.
        MESSAGE E000(38) WITH 'Error in Opening file: ' V_PHY_FILENAME.
      ENDIF.

  • Open Data Set Error while trying to read file from non SAP server

    Hi all,
    is it possible to read data from non-SAP application Sever?
    I'm using OPEN DATASET p_filin FOR INPUT IN LEGACY TEXT MODE CODE PAGE '1504',
    Where p_filin is other Windows server.Our applicition server is under Unix.Is it a problem?
    I make test to read file from SAP application server and it was ok.So how to call other server?
    Thanks!

    Hi,
    Yes it is possible to read data from a non SAP server through the statement OPEN DATASET.
    The important thing to check is that the SAP Server got enough access to the non SAP server so it can perform a reading/writing process depending on your needs.
    You should contact your network administrator and BASIS to help you check the permissions. This can be pretty tricky, specially if the servers are in different domains.
    Regards,
    Gilberto Li

  • How to combine both DAQ AI signal, write and read file in single VI

    Hi
     I am the new user of LabVIEW version 7.1 for testing automation application. I have to measure 33 signals ( mostly analog like temp, pressure, etc...) from NI USB 6210 DAQ system and write in master file for future verfication.From real data or from master file back up have to write  one more file if only the signal reaches steady state , which will used for analysis and same signals to be read from this file parallely & make a waveform and/or table display format.
    Pl. help me to shortout this problem 
    note: I have plan to ugrade labVIEW version 2011 shortly, so let me know doing parrel acquistion write and read file for data analysis in same VI in version 7.1...... 

    Parallel operations in LabVIEW are very simple.  Just code it in parallel and it will work.
    Try taking a look at some of the examples in the NI Example Finder (Help > Find Examples).  There you will find example for writing to and reading from files, as well as data acquistion in parallel with other operations.
    You might need a producer/consumer architecture is you are acquiring data very quickly.
    Chris
    Certified LabVIEW Architect
    Certified TestStand Architect

  • With conversion to Leopard, file problems with networked Windows computer

    Last night I did an Archive & Install from Tiger to Leopard on my Intel MacBook Pro. Today, I had trouble finding the other computers at my office. Once I finally got them to show up, I opened a Word file found on another computer, made some changes, and when I tried to save it, I got this message: "This is not a valid file name. Try one or more of the following: *Check the path to make sure it was typed correctly. *Select a file from the list of files and folders." Since this file already existed and I wasn't changing the name, I thought this was odd, but I changed the name from "Seating Chart 3-8-08" to "SeatingChart3-8-08" in case Leopard didn't like spaces when talking to Windows, but I got the same error message. Finally I gave up, not knowing what to do, then discovered that it had in fact saved my file. Still, every time I try to save ANY Word document from the shared folder of the Windows computer, I get the same error message endlessly until I choose "Don't Save."
    When I try to open an Excel file from that computer, it won't even open; it says " 'File Name.xls' cannot be accessed. This file may be Read-Only, or you may be trying to access a Read-Only location. Or, the server the document is stored on may not be responding." As with the Word file problem above, I did not have any problem accessing the files until I converted to Leopard.
    The Windows machine is Windows XP using Microsoft Office 2003; I have Microsoft Office 2004 on my machine.

    See if this Link, by Pondini, offers any insight to your issue...
    Transfer from Old  to New
    http://pondini.org/OSX/Setup.html
    Also, See here if you haven't already...
    http://www.apple.com/support/switch101/     Switching from PC

  • Null Pointer Exception Trying to Read File?

    I get a Null Pointer Exception when I try to perform the read hex2.txt, which i know exists and is in the same folder as this java file. Anyone see where my problem is?
    <code>
    import java.io.*;
    public class BytesToZeros
              int count = 0;
              int[] data;
              public static void main (String[] args)
                        BytesToZeros btz = new BytesToZeros();
              public BytesToZeros()
                        this.readFile();
                        this.writeFile();
              private void readFile ()
                        try
                                  FileInputStream fis = new FileInputStream("hex2.txt");
                                  BufferedInputStream bis = new BufferedInputStream(fis);
                                  boolean eof = false;
                                  while (!eof)
                                            int input = bis.read();
                                            if (input == -1)
                                                 eof = true;
                                            else
                                                 data[count] = input;
                                                 count++;          
                                  bis.close();
                        catch (IOException e)
                                  System.err.println("Error Reading File: " + e.getMessage());
                                  count = 0;
              private void writeFile ()
                        String zeros;
                        try
                                  FileOutputStream fos = new FileOutputStream("hex2.txt");
                                  BufferedOutputStream bos = new BufferedOutputStream(fos);
                                  for (int i=0; i<data.length; i++)
                                            bos.write(0);
                                  bos.close();
                        catch (IOException e)
                                  System.err.println("Error writing file: " + e.getMessage());
    </code>

    Doesn't the stack trace you get show which line it was thrown from?
    That should tell you where the problem is.
    It's weird to do a file read and a file write in the constructor like that. It would make somewhat more sense to do
    public static void main (String[] args) {
      BytesToZeros btz = new BytesToZeros();
      btz.readFile();
      btz.writeFile();
    }Although I realize this is just a test.
    Finally, to quote code use square brackes around the code tags:
    &#91;code]&#91;/code]

  • How to add Mac27" to existing home network? and read files on other PC computers (Window7)

    How to add Mac27" to existing home network? and read files on other PC computers (Window7).
    type of connection:
    All computer (PC & Mac) connect to router (ethernet or wireless), then connect to internet.
    condition:
    internet works fine on all computer (PC & Mac).
    existing 4 PC communicate well (share files & printers),
    my problem:
    can NOT add Mac into existing home network.
    I tried SYSTEM PREFERENCES, then NETWORK, then ......... several times
    could not make it work.
    pleas help.

    Ah, it looks like I should have read your title more carefully. Are the  files on the PCs that you want to share with your iMac in a shared folder?
    If not, follow the steps on this page to set up shares from Windows 7.
    If that is already set up, connect to the share from the iMac using this article.

  • Issue in lsmw ; error in read file step

    hi,
    i 'm facing some really strange issue in lsmw..
    i have created one header structure and 3 sub structures.
    until now its working fine
    but when i created 4th sub structure and in the read file step, its giving the following error :
    "Generation aborted. Reason: No fields with equal names"
    again if i delete that extra structure, its working fine..
    i really don't understand whats the problem... is there any restriction on number of structures?
    i need ur help guys
    Thanks in advance
    shekhar

    In step 13 Create Batch Input Session .....select Keep Batch input folder check box and goto step14 Run batch Input Session ....
    Slect your session name and click on Process....it will give one window and select Display Errors Only....then it will execute without press enter every screen...if any error is there it will stop and display error screen.
    Mohan

  • PSE 8 - How do I fix the error message: An error has occurred reading files or writing to disk...?

    Hello
    I am using Photoshop Elements 8 on Windows 7 (64 bit). I have all my photos stored on an external hard drive connected by usb. The photos were transferred onto the HDD from a Windows XP machine. I bought a new computer  so I installed Photoshop 8 and imported all my photos to the organiser from the HDD. I have also taken some photos yesterday which I have uploaded to the HDD.
    Now, when I want to delete a photo I check the box to say I want it to be deleted on the hard disk and I get the error message: 'An error has occured while reading files or writing files to disc. The disc may be full or there may bea problem with the source media.' This does not happen with the photos I uploaded yesterday, only the ones which were put onto the HDD from the XP machine.
    Please could someone help? I have tried the File>Catalog> repair and optimise functions. I have reinstalled the software. It still does the same.
    Thank you in advance
    Dave

    David GW wrote:
    The error message goes on to say, Please check your device settings or consult your device documentation regarding resolving writing errors. Which device do you think they are referring to?
    Sorry, but I would have thought that this was rather obvious! The only device capable of being written to under these circumstances is your CD drive; after all, it's a CD you are trying to create...
    You have two potential major causes of problems here. The most common cause of these difficulties is the disks themselves - you only need a batch with poor reflectivity to cause all sorts of read errors, so that's the first thing to try - using a different brand of disk to write to. The second thing you have to realise is that CD writers have a finite life - the lasers in them simply don't last for ever, and towards the end of their lives the power behaviour tends to be a bit erratic, and it tends to fall off somewhat - which causes the same sorts of errors, simply because the dye doesn't get evaporated efficiently. This causes mis-formed pits, hence the read errors. The only solution here is to install a new drive.
    When it comes to reading, commercial CDs have a much higher reflectivity than ones you write yourself, so often these will play whilst your own will fail - a common cause of confusion, this. But it's worth checking; if you get failures to reproduce all of the tracks from a commercial pressed CD, then almost certainly your drive is failing.

Maybe you are looking for

  • Can I use my iPad charger (12W) for my iPhone 6 plus?

    Can I use my iPad charger (12W) for my iPhone 6 plus?

  • Multiple Select boxes in one form

    Does anyone know if it is possible to have multiple select boxes inside one form? I have six different select boxes that are generated by six separate queries. The action page for all six select boxes is the same so I just want one submit button so u

  • SAP BI : Roles & Authorizations

    Hi, I am working on roles & authorizations for SAP BI 7.0 How can I create authorization for a scenario mentioned below: One user (userid ALAN) has two vendors under him viz V001 & V001A. V001 has access to plant A001, A002 and V001A has access to pl

  • Problems with moving images, widgets and text.

    Apologies if this question has already been asked. I think there has been a similar question asked but can't see a solution and I'm not sure if my problem is slightly different. I have been designing a Muse website on a MacBook Pro, and placing widge

  • CAT2: Restrict through P_PERNR

    Hi Experts, I want to restrict the user by using CAT2 transaction only for their personnel no. For that i maintained user parameter CVR & PER in SU3 and it worked fine by defaulting DATA ENTRY PROFILE & PERSONNEL NO. Now, I have to set authorization