Read txt files in DoJa?

I don't know if this is the right place to post this, but I haven't found any DoJa topic neither have I found good DoJa forums. So I thought I post it here.
My problem is: I'm trying to read and write .txt files in DoJa. I've wrote this script in JCreator (with other imports ofcourse), and it worked perfectly. But as I already expected it won't work in javaaplitool (2.5):
import com.nttdocomo.io.*;
import com.nttdocomo.ui.*;
class ReadFile
void ReadMyFile()
DataInputStream data_input_stream = null;
String input = null;
try
File file = new File("testfile.txt");
FileInputStream input_stream = new FileInputStream(file);
BufferedInputStream buffered_input_stream = new BufferedInputStream(input_stream);
data_input_stream = new DataInputStream(buffered_input_stream);
while ((input=data_input_stream.readLine()) != null)
System.out.println(input);
I've tried other things but it won't do and I'm not an expert in this :-(. Anyone know how to do it or have a small sample script or anything that can help?
Any help is greatly appreciated!

You're not doing it correctly. Use getClass().getResourceAsStream("yourtext.txt") to read data. Note that you cant just read files on phones, Java runs in a sandbox and only has access to files includes in tje Midlet JAR.

Similar Messages

  • Reading TXT files on WEBmode

    Hy
    My problem is to read TXT-Files in Webmode. In Client-Server mode it works fine. I use the function "text_io". In Webmode i get an error "No data found" (i think it is FRM-40375).
    In which virtual directory should the files placed on the OAS????
    Does anybody have some examples for me???

    You need to specify the directory unless your files are in the current working directory of the servlet container.
    The following can help you see some of your application context:
            // Get the server configuration information and display it.
            String thisServer= getServletConfig().getServletContext().getServerInfo();
            System.out.println("The servlet Engine version: " + thisServer);
            // What is the servlet root path ?
            String prefix =  getServletContext().getRealPath("/");
            System.out.println("prefix = '" + prefix + "'");
            // What is the app root ?
            String AppRootDir = getServletConfig().getServletContext().getRealPath("/");
            System.out.println("The app root directory : " + AppRootDir );

  • Is it possible to read txt files on the new ipod nano? as it was on the 5th gen

    is it possible to read txt files on the new ipod nano? as it was on the 5th gen.

    We won't know for sure until either the iPod is released and somebody can verify that or when the manual is available online from Apple.
    B-rock

  • How do I read txt file and add items to dropdownlist or checkbox

    I want to add items to a dropdown or check box by reading from a text file(and select one of them). (I donot use any table or database). The list of items is sometimes upto 20MB and hence cannot populate using session bean.I want items to be added to either checkbox or listbox during a button action. I have done this for textarea but unable so far to acheive for checkbox or listbox. I use following code which does not work:
    public String button3_action() {       
    try{           
    FileReader fr = new FileReader "F:/CreatorProjects/checkboxtst.prs");
    BufferedReader br = new BufferedReader(fr);
    String s;
    while((s=br.readLine())!=null) {
    dropdown1.setValue(s);
    br.close();
    fr.close();
    }catch(Exception e) {
    e.printStackTrace();
    return null;
    I know I cant just transplant textarea code for dropdownlist or checkbox.
    Any help is greatly appreciated.
    Thanks.
    Dr.AM.Mohan Rao

    I am able to read from txt file to a listbox if i write in sessionsbean1:
    try{
    FileReader fr = new FileReader("F:/CreatorProjects/checkboxtst.prs");
    BufferedReader br = new BufferedReader(fr);
    String s1="";
    String s="";
    while((s=br.readLine())!=null) {
    s1 = s1+s;
    s1= s1+"\n";
    disOptions = new com.sun.rave.web.ui.model.Option[] {              
    new Option(s1,s1)};
    diseases = new String[] {};
    fr.close();
    br.close();
    catch(Exception e) {
    e.printStackTrace();
    But I get all data in one line!! if I click submit button text area gets all. How to display items in each line????Please help...
    Dr.AM. Mohan Rao

  • Reading .txt file from remote using abap?

    Hi,
    I must read a .txt file from remote server automatically.
    I have path and name of .txt file. Remote system asks username and password.
    In abap is it possible to give username and password for reading .txt from remote server?
    Remote server and sap server are not in same domain.
    How can i do that?
    Thanks.

    Hi Cemil ,
      You can try using the FM RZL_READ_FILE_REMOTE_SH.
    This is an option i found ,  but i have really not tried it out .
    Regadrs
    Arun

  • Reading .txt file and non-english chars

    i added .txt files to my app for translations of text messages
    the problem is when i read the translations, non-english characters are read wrong on my Nokia. In Sun Wireless Toolkit it works.
    See the trouble is because I don't even know what is expected by phone...
    UTF-8, ISO Latin 2 or Windows CP1250?
    im using CLDC1.0 and MIDP1.0
    What's the rigth way to do it?
    here's what i have...
    String locale =System.getProperty("microedition.locale");
    String language = locale.substring(0,2);
    String localefile="lang/"+language+".txt";
    InputStream r= getClass().getResourceAsStream("/lang/"+language+".txt");
    byte[] filetext=new byte[2000];
    int len = 0;
    try {
    len=r.read(filetext);
    then i get translation by
    value = new String(filetext,start, i-start).trim();

    Not sure what the issue is with the runtime. How are you outputing the file and accessing the lists? Here is a more complete sample:
    public class Foo {
         final private List colons = new ArrayList();
         final private List nonColons = new ArrayList();
         static final public void main(final String[] args)
              throws Throwable {
              Foo foo = new Foo();
              foo.input();
              foo.output();
         private void input()
              throws IOException {
             BufferedReader reader = new BufferedReader(new FileReader("/temp/foo.txt"));
             String line = reader.readLine();
             while (line != null) {
                 List target = line.indexOf(":") >= 0 ? colons : nonColons;
                 target.add(line);
                 line = reader.readLine();
             reader.close();
         private void output() {
              System.out.println("Colons:");
              Iterator itorColons = colons.iterator();
              while (itorColons.hasNext()) {
                   String current = (String) itorColons.next();
                   System.out.println(current);
              System.out.println("Non-Colons");
              Iterator itorNonColons = nonColons.iterator();
              while (itorNonColons.hasNext()) {
                   String current = (String) itorNonColons.next();
                   System.out.println(current);
    }The output generated is:
    Colons:
    a:b
    b:c
    Non-Colons
    a
    b
    c
    My guess is that you are iterating through your lists incorrectly. But glad I could help.
    - Saish

  • Reading .txt file on Windows Server 2008

    I have a Java 7 application that we distribute, and it reads configurations from a .txt file distributed with it, in the same directory as the .jar file. On Windows 7, windows XP, Windows 8, this works fine, but on our server, running Windows Server 2008, this fails. It is a simple check that fails:
    Path p = Paths.get("config.txt");
    if(Files.isReadable(p))
    This will not work on Windows Server 2008 r2. It suspect that it somehow hasn't got read permissions, but I'm not sure.
    It also fails if the absolute path is specified.

    And what if you use the regular old fashioned standard IO File class and not Files to check if the file is readable (File.canRead())?
    Methinks (or to be honest: I guess) there is something odd with the creation of the Path object on your windows server file system, but I wouldn't be able to tell what exactly.

  • [CS3 JS]  Reading TXT file content into String

    Hello,
    I'm currently wanting to display a dialog box that has a dropdown menu containing all countries of the world.
    I have an external txt file that contains a list of all countries.
    I thought I would simply read-in the contents of the 'txt' file into a string and use it for displaying the list.
    For example
    i Instead of the usual:
    > var myLandMenu = dropdowns.add({stringList:["A", "B"...], selectedIndex:0});
    i I thought of doing something like:
    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    Is this the way to do it?
    What would be the way to read in the text file content as a string?
    Thanks in advance,
    Lee

    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    It's hard to tell from context, but myLandList needs to be an array of strings.
    If the file has one element per line, this would be one way of handling the
    conversion:
    var file = File("~/countries.txt");
    file.open("r");
    var str = file.read();
    file.close();
    var myLandList = str.split(/[\r\n]+/);
    And assuming that this is ScriptUI and not the older ID UI, the menu creation
    would look more like:
    var myLandMenu = dropdowns.add(bounds, myLandList);
    myLandMenu.items[0].selected = true;
    -X
    for photoshop scripting solutions of all sorts
    contact: [email protected]

  • Problem reading .txt-file into JTable

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
    public TeamTable()                {
    super( "Invoermodule - Team Table" );
    setSize( 740, 365 );
              // setting the rownames
    ListModel listModel = new AbstractListModel()                     {
    String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
    "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
    public int getSize() { return headers.length; }
    public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    A MORE READABLE VERSION !
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
        public TeamTable()                {
            super( "Invoermodule - Team Table" );
            setSize( 740, 365 );
              // setting the rownames
            ListModel listModel = new AbstractListModel()                     {
                String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
                "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
                public int getSize() { return headers.length; }
                public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

  • Writing and reading txt file, GUI components

    <b>HI GUYS I AM JUST NEW TO JAVA AND I AM TRYING TO LEARN SOME MORE IN JAVA. SO I NEED HELP FROM YOU GREAT GUYS WHO KNOWS MORE & MORE THING THAN ME. I CODE A GUI FOR THIS PROGRAM. THE CODE IS BELOW. <b/>
    This program has to read a txt file to create Food objects which will consist of a food name, a serving size, and a number of calories. A text file is read which contains the calories contained in specific food items. From this data, an array of Food objects will be created and used to populate a combo box for user selection. The Food objects will also be used in calculating the balance calories for a given user on a given day.
    User input will be used to create User objects which will be user name, age, gender, height, weight, and Food Diary objects (composition). The Food Diary objects will consist of Date (composition), Food object (composition), number of servings, and a balance. Food Diary objects will consist of the activity on any given day (see text area in sample output screen below). All User objects are saved to a file as objects and can be retrieved on subsequent runs of the program.
    The program will calculate the number of calories the user is allowed per day to maintain the user�s current weight (see below for formula to use for this).
    BMRMen = 66 + (13.7 * weightPounds/2.2) + (5 * heightInches*2.54) - (6.8 * age)
    BMRWomen = 655 + (9.6 * weightPounds/2.2) + (1.8 * heightInches*2.54) - (4.7 * age)
    GUI CODE
    <code>
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FoodDiaryGUI extends JFrame implements ActionListener {
    JLabel lblName, lblAge, lblWeight,lblHeight,lblFemale,lblMale,lblFood;
    JTextField txtName, txtAge, txtWeight,txtHeight;
    JButton btnSave, btnNewUser;
    JTextArea outputArea;
    JComboBox cbFood;
    int currentIndex=0, lastIndex=4;
    public FoodDiaryGUI()
    super ("Food Diary Calculator");
    lblName= new JLabel("Name: ");
    lblAge= new JLabel("Age: ");
    lblWeight= new JLabel("Weight(lbs): ");
    lblHeight= new JLabel("Height(inches): ");
    lblFemale= new JLabel("Female: ");
    lblMale= new JLabel("Male: ");
    lblFood= new JLabel("Choose a Food: ");
    txtName= new JTextField(15);
    txtAge= new JTextField(3);
    txtWeight= new JTextField(6);
    txtHeight= new JTextField(6);
    outputArea= new JTextArea(9,20);
    cbFood= new JComboBox();
    cbFood.setPreferredSize(new Dimension(100, 20));
    Container c = getContentPane();
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout());
    btnSave= new JButton("SAVE");
    northPanel.add(btnSave);
    btnNewUser= new JButton("NEW USER");
    northPanel.add(btnNewUser);
    btnSave.addActionListener(this);
    btnNewUser.addActionListener(this);
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new FlowLayout());
    centerPanel.add(lblName);
    centerPanel.add(txtName);
    centerPanel.add(lblAge);
    centerPanel.add(txtAge);
    centerPanel.add(lblWeight);
    centerPanel.add(txtWeight);
    centerPanel.add(lblHeight);
    centerPanel.add(txtHeight);
    centerPanel.setLayout(new FlowLayout());
    JRadioButton rbMale = new JRadioButton(maleString);
    birdButton.setMnemonic(KeyEvent.VK_M);
    birdButton.setActionCommand(maleString);
    birdButton.setSelected(true);
    JRadioButton rbFemale = new JRadioButton(femaleString);
    catButton.setMnemonic(KeyEvent.VK_F);
    catButton.setActionCommand(femaleString);
    //Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(rbMale);
    group.add(rbFemale);
    //Register a listener for the radio buttons.
    rbMale.addActionListener(this);
    rbFemale.addActionListener(this);
    public void actionPerformed(ActionEvent rb) {
    picture.setIcon(new ImageIcon("images/"
    + rb.getActionCommand()
    + ".gif"));
    radioGroup.add(rbMale);
    radioGroup.add(rbFemale);
    centerPanel.add(rbMale);
    centerPanel.add(rbFemale);
    centerPanel.add(lblFood);
    centerPanel.add(cbFood);
    JPanel southPanel = new JPanel();
    southPanel.setLayout(new FlowLayout());
    southPanel.add (outputArea);
    c.add(northPanel,BorderLayout.NORTH);
    c.add(centerPanel,BorderLayout.CENTER);
    c.add(southPanel,BorderLayout.SOUTH);
    setSize(650,300);
    setVisible(true);
    //add listener to button components.
    public void actionPreformed(ActionEvent e)
    if (e.getSource()==btnSave)
    currentIndex++;
    currentIndex--;
    public static void main (String[] args)
    FoodDiaryGUI application = new FoodDiaryGUI();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    </code>
    THE .txt file is as:
    1000 ISLAND, SALAD DRSNG,LOCAL*1 TBSP*25
    1000 ISLAND, SALAD DRSNG,REGLR*1 TBSP*60
    100% NATURAL CEREAL *1 OZ*135
    40% BRAN FLAKES, KELLOGG'S*1 OZ*90
    40% BRAN FLAKES, POST*1 OZ*90
    ALFALFA SEEDS, SPROUTED, RAW*1 CUP*10
    ALL-BRAN CEREAL*1 OZ*70
    ALMONDS, WHOLE*1 OZ*165
    ANGELFOOD CAKE, FROM MIX*1 PIECE*125
    APPLE JUICE, CANNED*1 CUP*115
    i hope this forum site has to many java professionals and this problem is nothing for them. for me it is great.

    Stick to using a single userid and a single posting of a question:
    http://forum.java.sun.com/thread.jspa?threadID=731264&tstart=0

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

  • Reading .txt file Server side

    How do you read a file server side and send it to the client. I am getting confused with FileReader and the fact that you have to wrap a socket with PrintWriter, BufferedWriter and OutputStreamWriter i.e.
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    Any ideas

    Assuming you want to read from a file on the server and write to a client socket:
    FileReader fi= new FileReader("reading.txt");
    BufferedReader br= new BufferedReader(fi);
    String il=br.readLine();
    ServerSocket sock= new ServerSocket(port,mcons);
    PrintStream dout=
    new PrintStream (sock.getOutputStream());
    dout.println(il);
    dout.flush();...
    Hope this helps.

  • Reading txt file - FileNotFoundException

    Hi,
    I'm new to java and am in need of some help. I'm writing a programme that involves reading one or more txt files in from the command line. I've tried doing this a number of ways, but seem to butt up against the same error - java cannot find my test file and returns
    java.io.FileNotFoundException test.txt when it runs.
    here's a code snippet - from a test class, not the programme, but the code produces the same problem:
    BufferedReader inputFile = new BufferedReader (new FileReader ("test.txt"));
    while ((input = inputFile.readLine())  != null)
         input = input.trim();
         System.out.println(input);
    inputFile.close();test.txt is in the same directory as the class. I've tried explicitly defining the path, with appropriate escape chars, which hasn't helped. also,
    System.out.println(file.getCanonicalPath());  returns the correct path, and
    System.out.println(file.exists());returns false.
    It seems that the file really isn't there. Except that I know it is. I think this is almost certainly something very simple that i'm missing, but i'd appreciate any help anyone can offer.
    cheers,
    dan

    this is part of the main code - it used a scanner object instead of a buffered reader, which i found out about while looking for a fix to the problem. the exception produced is the same, in any case. I've commented the relevant sections
    default:
                        inFile = numFiles - 2;
                        outputFile = files[numFiles - 1];
                        isStdOut = outputFile.matches("-");
                        for (int fileNum = 0; fileNum < inFile ; fileNum ++)
                             Scanner inputFile = new Scanner( new File (files[fileNum]) );  //sets up the input file, which is in the String[ ] files, the //command line list of input and output files
                             firstLineIn = inputFile.nextLine();
                             isStdIn = control.checkFile( files[fileNum], firstLineIn );
                             control.resetCurrent();
                             if (isStdIn)
                                  while (input.equalsIgnoreCase("end") == false)
                                       input = control.stdIn();
                                       input = input.trim();
                                       control.processCommand(input, isStdOut, musak, outputFile);
                             else
                                  while (inputFile.hasNext())     // -- treats the text as an iterator object, processes each line.  
                                       input = inputFile.nextLine();
                                       input = input.trim();
                                       control.processCommand(input, isStdOut, musak, outputFile);
                        break;
                   }the other test code is really as before - it uses the string constructor as you say. the check for existence is just something i put in to verify for myself.
    let me know if this is helpful or not...

  • Reading txt file coordinates into chart...

    Hi, I'm currently making a GUI which displays a graph. At the moment it reads coordinates within an array in the code:
        public int datax[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        public int datay[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; So far I've made it read in a txt file and output to a text area like this:
        public void readFile() {
                 // Disable read button
                  readFile.setEnabled(false);
            // Dimension data structure
         getNumberOfLines();
         data = new String[numLines];
         // Read file
         readTheFile();
         // Output to text area     
         textArea.setText(data[0] + "\n");
         for(int index=1; index < data.length;index++)
             textArea.append(data[index] + "\n");
         // Rnable open button
         openFile.setEnabled(true);
          }My code to plot the coordinates using datasets is this:
    //Configure dataset
        int n = 10;
             Dataset dataset = new Dataset (1, 2, n);
                for (int k = 0; k < n; ++k)
             dataset.set(0, 0, k, datax[k]);
                for (int k = 0; k < n; ++k)
             dataset.set(0, 1, k, datay[k]); I need datax and datay to be read in from the txt file though which is formatted simply x val, y val [per line].
    I know this should be straightforward, but I just can't see how to do it. Can anyone possibly suggest a solution?
    Lev

    A list of Point objects?
    The points need to be read in from a txt file which looks like
    9, 5
    2, 3
    7, 3
    3, 5
    2, 5.. etc so even if it was read into an array, then into the graph, that would probably work..
    The code isn't ready to accept that format yet, but I'm hoping someone can suggest a method to output
    to the graph instead of the text field. As you can tell, some areas of Java I get, some I definately don't :'(

  • "Bad data format" when reading txt file from the presentation server

    Hello,
    I have a piece of code which reads a txt file from the presentation server to an internal table like below:
    DATA : lv_filename type string.
    lv_filename = 'C:\abap\Test.txt'. "I created a folder called abap under C:\
    CALL method CL_GUI_FRONTEND_SERVICES=>GUI_UPLOAD
    EXPORTING
       FILENAME              = lv_filename
    CHANGING
       DATA_TAB            = lt_tsd. " lt_tab has the exact same fields as the Test.txt's. Test.txt has only one line, tab delimited.
    When running this code, exception BAD_DATA_FORMAT is issued.
    Is it because of the file encoding or delimiter or other reason?
    Thanks,
    Yang

    Hello,
    If its tab delimited then use the has_field_seperator parameter and check
    DATA : lv_filename type string.
    lv_filename = 'C:\abap\Test.txt'. "I created a folder called abap under C:\
    CALL method CL_GUI_FRONTEND_SERVICES=>GUI_UPLOAD
    EXPORTING
       FILENAME                = lv_filename
       FILETYPE                 = 'ASC'
       HAS_FIELD_SEPARATOR          = u2018Xu2019
    CHANGING
       DATA_TAB            = lt_tsd.
    Vikranth

Maybe you are looking for

  • Photo fails to open when I click on a thumbnail. Why?

    Many photos which are visible in a thumbnail - from an Event - will not open. Instead I get a black screen, on which is a black/grey exclamation mark. The date is visible but not the image. Why is this and what can I do?

  • Problem with Spry Tabbed Panels and Mac Safari

    On a site I'm working on I have implemented Spry Tabbed Panels. Everything was great until my boss looked at it on his Mac Safari. Spry doesn't seem to honor the 100% width, and cuts it off. I have looked at the CSS and don't see what is holding it u

  • W520 battery in a W530?

    My a few months ago my W520 blew up 4 days after the 3 year international NBD warranty expired (and lenovo told me they would not help me), so had to buy a W530.  The PSU from the 520 works on the 530, as does the dock, but the batteries wont charge.

  • OBI SE 1 Administration Tool as a client tool to another OBI SE1 instance

    Our client has installed the OBI SE 1 on a "server" machine with no hassles. They then installed OBI SE 1 again on a different "client machine", in order to use, only the Administration Tool as a client tool to the other OBI SE 1 Server instance. The

  • Is it possible to set a field in another item/list in a workflow?

    I've created a list workflow to add a task after a new client is added to my client list. I am trying to create a pre-determined due date, so that the workflow works out the due date so that it's 2 days from today. So I decided to use the 'Add time t