Friday, April 15, 2011

Read from file in eclipse

Hi,

I'm trying to read from a text file to input data to my java program. However, eclipse continuosly gives me a Source not found error no matter where I put the file.

I've made an additional sources folder in the project directory, the file in question is in both it and the bin file for the project and it still can't find it.

I even put a copy of it on my desktop and tried pointing eclipse there when it asked me to browse for the source lookup path.

No matter what I do it can't find the file.

here's my code in case it's pertinent:

System.out.println(System.getProperty("user.dir"));
 File file = new File("file.txt");


 Scanner scanner = new Scanner(file);

in addition, it says the user directory is the project directory and there is a copy there too.

I have no clue what to do.

Thanks, Alex

after attempting the suggestion below and refreshing again, I was greeted by a host of errors.

FileNotFoundException(Throwable).<init>(String) line: 195
FileNotFoundException(Exception).<init>(String) line: not available FileNotFoundException(IOException).<init>(String) line: not available
FileNotFoundException.<init>(String) line: not available
URLClassPath$JarLoader.getJarFile(URL) line: not available
URLClassPath$JarLoader.access$600(URLClassPath$JarLoader, URL) line: not available
URLClassPath$JarLoader$1.run() line: not available
AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] URLClassPath$JarLoader.ensureOpen() line: not available URLClassPath$JarLoader.<init>(URL, URLStreamHandler, HashMap) line: not available
URLClassPath$3.run() line: not available
AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] URLClassPath.getLoader(URL) line: not available URLClassPath.getLoader(int) line: not available URLClassPath.access$000(URLClassPath, int) line: not available
URLClassPath$2.next() line: not available
URLClassPath$2.hasMoreElements() line: not available
ClassLoader$2.hasMoreElements() line: not available CompoundEnumeration<E>.next() line: not available
CompoundEnumeration<E>.hasMoreElements() line: not available
ServiceLoader$LazyIterator.hasNext() line: not available
ServiceLoader$1.hasNext() line: not available
LocaleServiceProviderPool$1.run() line: not available
AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] LocaleServiceProviderPool.<init>(Class<LocaleServiceProvider>) line: not available
LocaleServiceProviderPool.getPool(Class<LocaleServiceProvider>) line: not available NumberFormat.getInstance(Locale, int) line: not available
NumberFormat.getNumberInstance(Locale) line: not available
Scanner.useLocale(Locale) line: not available
Scanner.<init>(Readable, Pattern) line: not available
Scanner.<init>(ReadableByteChannel) line: not available Scanner.<init>(File) line: not available
code used:

System.out.println(System.getProperty("user.dir"));
 File file = new File(System.getProperty("user.dir") + "/file.txt");


 Scanner scanner = new Scanner(file);
From stackoverflow
  • Have you tried using an absolute path:

    File file = new File(System.getProperty("user.dir") + "/file.txt");

  • Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

    When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

    Also, if you're in Linux, remember that its file systems are usually case sensitive.

    Buzkie : I think the problem was I had refreshed the src and files file, but not the project file, so it never found it. thanks for the help
    Pablo Santa Cruz : Did it solve your problem?
    Buzkie : yes it works now
  • There's nothing wrong with your code, the following works fine for me when I have the file.txt in the user.dir directory.

    import java.io.File;
    import java.util.Scanner;
    
    public class testme {
        public static void main(String[] args) {
            System.out.println(System.getProperty("user.dir"));
            File file = new File("file.txt");
            try {
                Scanner scanner = new Scanner(file);
            } catch (Exception e) {
            System.out.println(e);
            }
        }
    }
    

    Don't trust Eclipse with where it says the file is. Go out to the actual filesystem with Windows Explorer or equivalent and check.

    Based on your edit, I think we need to see your import statements as well.

  • You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

    If you whish to read the file in a given directory, you have to says so :

    File file = System.getProperty("user.dir")+"/"+"file.txt";
    

    You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

    Note that there is also a property for the separator (hard-coded to "/" in my exemple)

    regards Guillaume

how can I access the formula in an excel sheet with c#?

I am parsing thorugh a 2000+ record excel file, and need ot be able to grab the formula itself from the cells and not just the value. For example, one cell 'Contributions' may be a single number like 1500 or it can be a few numbers 1500+500-200 but I dont want the total, I want the actual formula so I can get the different numbers.

I was just parsing with an oledbconnection and that only seems to get me the total. How would I go about getting the formula? Is it possible (I can get it in either XLS or XLSX)?

Thank you.

From stackoverflow
  • A quick google found the following: http://codingsense.wordpress.com/2009/03/01/get-all-formula-from-excel-cell/

    Stuck In Baghdad : grrrrr... blocked from work, I'll have to check this from home
  • The xslx is an xml file so it should be easy enough to read. Alternatively you can use third-part components like the one from Infragistics that allows you to read xsl-files programmatically and also to access the formulas.

  • Using OLE Automation, you can access the formula in a cell as follows:

    formula = worksheet.Cells(1, 1).Formula
    

    EDIT:

    To use OLE Automation in your C# project, see the following Microsoft KB article:

    Stuck In Baghdad : can you explain more about this? What kind of object is 'worksheet'? How do I get one :P

Winforms multithreading scenario question

Hello,

this morning I saw some strange code from one of my coworkers. In an winforms application the whole Mainform was given into a thread as reference. He did this to invoke methods from the Form. Nothing to interact with the UI, just plain calculation methods. I am already sure this is not a best-practice but I wonder something. If I call methods from the Mainform from inside a thread are these methods still processed as multithreading? Or do they run inside the Mainform? Will the UI thread be affected when I call methods from the Mainfrom from a thread?

From stackoverflow
  • Functions from the form called from a different thread will run on the thread that is calling them and have no effect on the GUI thread. As a side effect, this means that if you call a function that interacts with the GUI you will get an exception.

    If you want them to be called on the GUI thread, the easiest thing to do is call Control.Invoke(...) which causes the delegate you pass in to be executed on the GUI thread, allowing GUI interaction.

Can NHibernate persist to flat files instead of database?

Here is a curiousity question. I have an application that must support both flat files and the database as a place to persist data. I was thinking maybe using a .csv or tab-delimited set of files as input ...

Is it possible to use NHibernate to write to do both persistance tasks?

From stackoverflow
  • No not to the best of my knowledge. I have the same requirement and have ended up just using flat XML files and hand rolling all the CRUD.

    Just today I did happen to notice this File System Database on codeplex but haven't looked into it properly yet.

  • Try using the Jet engine (see this)

    Dialect and other nhibernate settings should be the ones for Microsoft Access.

Hibernate rollbacks

If I do the following

session.getTransaction().rollback();

is it then ok/possible to start calling save/update/delete etc. on the same session object? Couldnt find the answer to this in the Hibernate Session/Transaction API, or in the Hibernate reference documentation.

Or do you recommend me to close that Session object, open a new Session and begin a new Transaction?

From stackoverflow
  • I'm not sure if this is possible/adviceable from a database point of view, but writing atomic code is so much better for readibility. You may even reuse the structure of a template method to forget about the wirings around your transaction.

  • I say close the session and open a new one. Hibernate is not known for being forgiving about abuse of its sessions. It may hurt performance a bit, but it will probably prevent a bug down the road.

    Yuval =8-)

Programatically loop through a DatagridView and check checkboxes

Hi ,

I have DataGridView bound by a datatable i have checkboxes to the same.

I want to navigate or loop through the the datagridview and check mark these checkboxes ,Below is the syntax i use .

foreach(DataGridViewRow dr in dgvColumns.Rows)
{
    DataGridViewCheckBoxCell checkCell =
        (DataGridViewCheckBoxCell)dr.Cells["CheckBoxes"];
    checkCell.Value=1;
    //Also tried checkCell.Selected=true;
    //Nothing seems to have worked.!
}
From stackoverflow
  • If it is bound to a DataTable, can you not work on the model (the table) instead? The DataGridView is a view...

    Try looping over the rows in the table, setting the values. For example (below) - note that I don't update the DataGridView - just the DataTable:

    using System;
    using System.Data;
    using System.Windows.Forms;
    
    static class Program
    {
        [STAThread]
        static void Main()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Selected", typeof(bool));
            table.Rows.Add("Fred", false);
            table.Rows.Add("Jo", false);
            table.Rows.Add("Andy", true);
    
            Button btn = new Button();
            btn.Text = "Select all";
            btn.Dock = DockStyle.Bottom;
            btn.Click += delegate
            {
                foreach (DataRow row in table.Rows)
                {
                    row["Selected"] = true;
                }
            };
    
            DataGridView grid = new DataGridView();
            grid.Dock = DockStyle.Fill;
            grid.DataSource = table;
    
            Form form = new Form();
            form.Controls.Add(grid);
            form.Controls.Add(btn);
            Application.Run(form);
        }
    }
    
    Marc Gravell : If it is data-bound, then changing the *bound* value should fix this too, I believe.
  • Something along the lines of:

    foreach(DataGridViewRow dgvr in dgvColumns.Rows)
    {
        // Get the underlying datarow
        DataRow dr = ((DataRowView)dgvr.DataBoundItem).Row;
    
        // Update the appropriate column in the data row.
        // Assuming this is your column name in your 
        // underlying data table
        dr["CheckBoxes"] = 1;
    }
    
    Justin Bannister : Sorry, the cast was wrong. I have amended the code above.
    Justin Bannister : Is the combo box data bound?
    Justin Bannister : Assuming you have populated the combo with data by adding items. Simply get a reference to the DataGridComboBoxCell and set the value of the item. But the item must be in the list.
  • The following worked for me, it checked the checkboxes perfectly :)

    foreach (DataGridViewRow row in dgvDataGridView.Rows)

         {
                 ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
    
          }
    

How to make WPF Expander Stretch?

The Expander control in WPF does not stretch to fill all the available space. Is there any solutions in XAML for this?

From stackoverflow
  • HorizontalAlignment="Stretch"
    
    Ngm : This is not working
  • All you need to do is this:

    <Expander>
      <Expander.Header>
        <TextBlock
          Text=”I am header text…”
          Background=”Blue”
          Width=”{Binding
            RelativeSource={RelativeSource
              Mode=FindAncestor,
              AncestorType={x:Type Expander}},
            Path=ActualWidth}”
          />
      </Expander.Header>
      <TextBlock Background=”Red”>
        I am some content…
      </TextBlock>
    </Expander>
    

    http://joshsmithonwpf.wordpress.com/2007/02/24/stretching-content-in-an-expander- header/

    Ngm : How do I do this in code? I realized that I have to account for some space for a button
    Jonathan Parker : Sorry I don't know how to do it in code.
    Josh G : TextBlock bx = new TextBlock(); bx.Text = "I am header text..."; Binding wdBind = new Binding("ActualWidth"); wdBind.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Expander), 1); bx.SetBinding(TextBlock.TextProperty, wdBind);
    Josh G : bx.Background = Colors.Blue; Expander ex = new Expander(); ex.Header = bx;
    Josh G : TextBlock contBx = new TextBlock(); contBx.Background = Colors.Red; contBx.Text = "I am some content..."; ex.Content = contBx;
    Josh G : ... This code is exactly equivalent to the XAML above.
    Jonathan Parker : Josh, you can always put this code in your own answer. That way it's more visible and can be voted on and marked as the answer.
  • Non stretchable Expanders is usually the problem of non stretchable parent controls.. Perhaps one of the parent controls has defined a HorizontalAlignment or VerticalAlignment property ?

    If you can post some sample code, we can give you a better answer..

    HTH

  • I Agree with HTH - check what sort of a container you're putting the Expander in... the StackPanel will always fold it's children down to the smallest size they can go to.

    I'm using Expanders a lot in my project, and if you drop them into a Grid / DockPanel, then the expander will fill all available space (assuming it's Vertical & Horizontal orientations are set to Stretch).

    Jonathan's suggestion of Binding the Expander's width to the container's width can get a bit tricky... I tried this technique a few weeks back and found that it can producte undesirable results in some cases, because it can inhibit the functioning of the layout system.

    PS: As a general tip (and I'm sure I'm gonna get flamed for writing this), if you're unsure of what sort of layout-container to your controls in, then start off with a Grid. Using the Column & Row definitions allows you to very easily control whether child controls use minimum space ("Auto"), maximum space ("*") or an exact amount of space ("[number]").

    Josh G : Grid is definitely the most versatile and easy to use container. I've heard that it performs much worse than most containers also.
    Bryan Anderson : @Mark, you mean you agree with Arcturus. HTH means Hope That Helps and is a common closing around here.
  • The Silverlight Toolkit includes an Accordion control which acts like an expander that always stretches to the available space. I haven't tested it yet, but it might be functional for WPF too, like the Silverlight Chart controls.