Cant Get My Program to Read a Text File

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class Calculator
    public static void main (String[] args)
        final String filepath = "calculator.txt";
        int a, b, x;
        String command;
        Scanner fileScan = new Scanner(new File(filepath));
        while (fileScan.hasNext())
            command = fileScan.nextLine();
            System.out.println(command);
}Thats the code I have so far. I have an input file called "calculator.txt" which I made in notepad then copy/pasted into the same folder that this Calculator.java file is located. The build fails and sends this error:
unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
What am I doing wrong that it cant read the file?

"Exceptions" are written about and described in any Java book and they all contain plenty of example.
Your code shows no attempt whatsoever to handle an Exception. So the original answer assumed you didnt' know what an Exception was and gave you a resource to read.
It you would spend the time reading your text or the tutorial given instead of wasting time with these ridiculous comments you would have had your answer by now.
We don't have time to write a personal explanation about what an Exception is. We would only be duplicating what is in the book and tutorial.
On the other hand if your code acutally contained some code that resembled an attempt to catch an Exception, then you might have been given more specific help. If you don't understand that concept then you will have trouble getting answers in the forum.
Did you even search the forum to see if any other posting had a question about that Exception?

Similar Messages

  • How do you get a program to read an input file?

    I have a problem where i need my program to read an input file and the name of the input file should be read as a command line argument. How in the world do I do this?? I do not have the slightest idea how to get that done? Please help!!

    The command line arguments are stored in the String[] args passed in from the main function.
    To use the argument as a file name, you can create a FileInputStream. To make it easier to read, you can then put the FileInputStream into a BufferedReader to read line by line. For example:
    public static void main(String[] args) {
       FileInputStream fileIn;
       BufferedReader reader;
       try {
          fileIn = new FileInputStream(args[0]);
       catch (FileNotFoundException fnfe) {
          System.err.println("could not find file " + args[0]);
       reader = new BufferedReader(fileIn);   You may now use reader.readLine() to read each line from the file. I hope this helps!
    -JBoeing

  • Java 2d to read a text file containing vrml

    Hi I was wondering if anyone could tell me how I can get have 2d to read a text file such as one in vrml.
    How would I go about doing this as right now i have 2 files which i want to integrate, a 2d plan and a vrml correspondant.
    Thanks in advance

    You pretty much posted this same question yesterday. You know you need to use String.split(). Why don't you give it a try and let us know what you did?
    I'm pretty sure you'll need to form your regular expression as "~#^\\$", because $ has special meaning inside a search expression.
    Oh, and please use the code tag when posting code.

  • I would like to read a text file in which the decimal numbers are using dots instead of commas. Is there a way of converting this in labVIEW, or how can I get the program to enterpret the figures in the correct way?

    The program doest enterpret my figures from the text file in the correct way since the numbers contain dots instead of commas. Is there a way to fix this in labVIEW, or do I have to change the files before reading them in the program? Thanks beforehend!

    You must go in the labview option menu, you can select 'use the local
    separator' in the front side submenu (LV6i).
    If you use the "From Exponential/Fract/Eng" vi, you are able to select this
    opton (with a boolean) without changing the labview parameters.
    (sorry for my english)
    Lange Jerome
    FRANCE
    "Nina" a ecrit dans le message news:
    [email protected]..
    > I would like to read a text file in which the decimal numbers are
    > using dots instead of commas. Is there a way of converting this in
    > labVIEW, or how can I get the program to enterpret the figures in the
    > correct way?
    >
    > The program doest enterpret my figures from the text file in the
    > correct way since the numbers contain dots instea
    d of commas. Is there
    > a way to fix this in labVIEW, or do I have to change the files before
    > reading them in the program? Thanks beforehend!

  • Where does this java program read a text file and how does it output the re

    someone sent this to me. its a generic translator where it reads a hashmap text file which has the replacement vocabulary etc... and then reads another text file that has what you want translated and then outputs translation. what i don't understand is where i need to plugin the name of the text files and what is the very first line of code?
    [code
    package forums;
    //references:
    //http://forums.techguy.org/development/570048-need-write-java-program-convert.html
    //http://www.wellho.net/resources/ex.php4?item=j714/Hmap.java
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class Translate {
    public static void main(String [] args) throws IOException {
    if (args.length != 2) {
    System.err.println("usage: Translate wordmapfile textfile");
    System.exit(1);
    try {
    HashMap words = ReadHashMapFromFile(args[0]);
    System.out.println(ProcessFile(words, args[1]));
    } catch (Exception e) {
    e.printStackTrace();
    // static helper methods
    * Reads a file into a HashMap. The file should contain lines of the format
    * "key\tvalue\n"
    * @returns a hashmap of the given file
    @SuppressWarnings("unchecked")
    private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    HashMap map = null;
    try {
    in = new BufferedReader(new FileReader(filename));
    String line;
    map = new HashMap();
    while ((line = in.readLine()) != null) {
    String[] fields = line.split("\\t", 2);
    if (fields.length != 2) continue; //just ignore "invalid" lines
    map.put(fields[0], fields[1]);
    } finally {
    if(in!=null) in.close(); //may throw IOException
    return(map); //returning a reference to local variable is safe in java (unlike C/C++)
    * Process the given file
    * @returns String contains the whole file.
    private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    StringBuffer out = null;
    try {
    in = new BufferedReader(new FileReader(filename));
    out = new StringBuffer();
    String line = null;
    while( (line=in.readLine()) != null ) {
    out.append(SearchAndReplaceWordsInText(words, line)+"\n");
    } finally {
    if(in!=null) in.close(); //may throw IOException
    return out.toString();
    * Replaces all occurrences in text of each key in words with it's value.
    * @returns String
    private static String SearchAndReplaceWordsInText(Map words, String text) {
    Iterator it = words.keySet().iterator();
    while( it.hasNext() ) {
    String key = (String)it.next();
    text = text.replaceAll("\\b"+key+"\\b", (String)words.get(key));
    return text;
    * @returns: s with the first letter capitalized
    String capitalize(String s)
    return s.substring(0,0).toUpperCase() + s.substring(1);
    }

    without what arguments?Without any arguments. If there are no arguments, there are no arguments of any kind. If you have a zoo with no animals in it, it's not meaningful to ask whether the animals which are not there are zebras or elephants.
    does it prompt me to give it a text file name?Apparently.
    when i run it this is all i get:
    usage: Translate wordmapfile textfile
    Press any key to continue...Right. And "wordmapfile" is almost certainly supposed to be a file that holds the word map, and "textfile" is almost certainly the file of text that it's going to translate.

  • I cant get the program to stop searching for a missing file

    i cant get the program to stop searching for a missing file

    You can uncheck the option that says automatically search for missing files in the prefernces window of Organizer.

  • I transfered my Final Cut Pro from a macbook to a new macbook pro and i cant get the program to open.

    I transfered my Final Cut Pro from a macbook to a new macbook pro and i cant get the program to open. I have already uninstalled a reinstalled 4 times. What should I do?

    How did you transfer it?
    As a first step you should trash the preferences with http://www.digitalrebellion.com/prefman/

  • I bought a used 160GB ipod and I cant get my computer to read it. What do I need to do?

    I bought a used 160GB ipod and I cant get my computer to read it. What do I need to do?

    Is your iTunes running the latest version? If not, but the iPod you've bought has been set up to work with the latest version, then iTunes probably will not recognise it.
    In iTunes, select Help/Check for updates. If there is a newer version, make sure you are running that before connecting the iPod again.
    If that isn't the problem - or more to the point - it doesn't fix the problem, post here again so that anyone watching it can suggest the next step.

  • How to open saved files using 'read from text file' function

    Hi everyone, I am having a hard time trying to solve the this particular problem ( probably because I am a newb to lanbview ). Anyway , I am able to save the acquired waveforms by using the 'Write to text file' icon. I did manually modify the block diagram of the 'Write to text file' icon and create the correct number of connector so as to make my program work. But now I have no idea on how to modify the block diagram of the 'Read from text file' block diagram to make my program 'open' my saved waveforms. Or i do not have to modify anything from the block diagram of the 'Read from text file'? Can anyone teach/help me connect up? Do i need the build array on the "open" page?
    Here are some screenshots on part of my program  
    let me know if you guys would need more information / screenshots thank you!
    Attachments:
    ss_save.jpg ‏94 KB
    ss_open.jpg ‏94 KB
    modified_writetotextfile.jpg ‏99 KB

    Ohmy, thanks altenbach. oh yeah i forgot about those sub VIs. will upload them now. Was rather demoralized after reading the comments and really struck me on how weak i'm at on labview really hope to get this done. But of course i have to study through and see how it works. Actually i am going to replace those 'signal generators sub vi' with ThoughtTechonology's sample code so i can obtain data waveforms real-time using Electrocardiography (ECG) ,Electromyography (EMG ) and Electroencephalography (EEG) hopefully i can find out how to connect the sample code.
    ( ps . cant connect it now unless my program is working otherwise labview will crash ) 
    ( p.s.s the encoder of my biofeedback trainer already acts as an DAQ so i wont need to place an DAQ assistant in my block diagram i suppose )
    The sample code of ThoughtTechnology is named as attachment.ashx.vi. too bad i cant use it and present it as my project
    Attachments:
    frequency detactor.vi ‏53 KB
    signal generator.vi ‏13 KB
    attachment.ashx.vi ‏40 KB

  • Read from text file vi won't read file...

    I am very new to LV programming so I hope you forgive any stupid mistakes I am making.   I am using Ver. 8.2 on an XP machine.
    I have a small program that stores small data sets in text files and can update them individually or read and update them all sequentially, sending the data out a USB device.   Currently I am just using two data sets, each in their own small text file.  The delimiter is two commas ",,".
    The program works fine as written when run in the regular programming environment.   I noticed, however, as soon as I built it into a project that the one function where it would read each file sequentially to update both files the read from text file vi would return an empty data set, resulting in blank values being written back into the file.   I read and rewrite the values back to the text file to place the one updated field (price) in it'sproper place.  Each small text file is identified and named with a 4 digit number "ID".   I built it twce, and get the same result.  I also built it into an installer and unfortunately the bug travelled into the installation as well.
    Here is the overall program code in question:
    Here is the reading and parsing subvi:
    If you have any idea at all what could cause this I would really appreciate it!
    Solved!
    Go to Solution.

    Hi Kiauma,
    Dennis beat me to it, but here goes my two cents:
    First of all, it's great to see that you're using error handling - that should make troubleshooting a lot easier.  By any chance, have you observed error 7 when you try to read your files and get an empty data set?  (You've probably seen that error before - it means the file wasn't found)
    If you're seeing that error, the issue probably has something to do with this:
    Relative paths differ in an executable.  This knowledge base document sums it up pretty well. To make matters more confusing, if you ever upgrade to LabVIEW 2009 the whole scheme changes.  Also, because an installer contains the executable, building the installer will always yield the same results.
    Lastly, instead of parsing each set of commas using the "match pattern" function, there's a function called "spreadsheet string to array" (also on the string palette) that does exactly what you're doing, except with one function:
    I hope this is helpful...
    Jim

  • Reading Windows text file in Fortran?

    Is there a way to make the f90 compiler read Windows text files properly? I made a simple test with a text file created on a Windows system containing these three lines:
    This is a Windows text file.
    It has some extra control characters.
    Unix does not have those.
    The output I got was:
    <-ext file.
    <-e extra control characters.
    <-se.
    Kevin

    That makes more sense. The problem isn't with the Fortran program, but with the Unix terminal (xterm, or whatever you're using to display the output). If you pipe the output through od like this you'll see all the characters, including the ^M:
    bash-3.00$ fortranread | od -c
    0000000       w   i   n   f   i   l   e       i   s       -   >   T   h
    0000020   i   s       i   s       a       W   i   n   d   o   w   s   
    0000040   t   e   x   t       f   i   l   e   .  \r                   
    0000060                                                               
    0000100                                           <   -  \n       w   i
    0000120   n   f   i   l   e       i   s       -   >   I   t       h   a
    0000140   s       s   o   m   e       e   x   t   r   a       c   o   n
    0000160   t   r   o   l       c   h   a   r   a   c   t   e   r   s   .
    0000200  \r                                                           
    0000220                               <   -  \n       w   i   n   f   i
    0000240   l   e       i   s       -   >   U   n   i   x       d   o   e
    0000260   s       n   o   t       h   a   v   e       t   h   o   s   e
    0000300   .  \r                                                       
    0000320                                                               
    0000340                   <   -  \n
    0000347When the terminal sees the ^M character, it does a carriage return. That means that the next character gets written in the first column. Since the characters after the ^M are spaces, that makes the beginning of the lines appear blank.
    If you want to see the output you expect, you need to pipe it through "tr -d '\015'", or you need to make the Fortran program itself delete the ^M characters. For example, you could write "myline(1:len_trim(myline)-1)" to always strip the last character of the line.
    We should consider making formatted reads strip the ^M by default. I don't know whether any program would actually want them.

  • Reading a text file with foreign language characters

    I'm trying to convert foreign language characters to English looking characters.  I have code that works, but only if I hard code the string with foreign language characters and pass it to the function. I cannot figure out how to get my program to read
    in the foreign characters from my file, they come in as garbage. 
    Since the function works when I pass a hard coded string to it, I'm pretty sure the problem is the way I have the Streamreader set up, it's just not reading the characters correctly...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FileRdr As StreamReader = New StreamReader "m:\test\charReplace.txt", System.Text.Encoding.UTF7)
    Dim ReplaceWrtr As StreamWriter ReplaceWrtr = System.IO.File.CreateText("M:\test\CharReplaceOut.txt")
    Do While FileRdr.Peek() >= 0
    Dim currentRec As String = FileRdr.ReadLine
    removeAccent(currentRec)
    ReplaceWrtr.WriteLine(currentRec)
    Loop
    ReplaceWrtr.Close()
    End Sub
    'Replace foreign language characters with English characters
    Function removeAccent(ByVal myString As String)
    Dim A As String = "--"
    Dim B As String = "--"
    Const AccChars As String = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    Const RegChars As String = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    For i As Integer = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    myString = Replace(myString, A, B)
    Next
    removeAccent = myString
    End Function
    I know that removing the accent changes the meaning of the word, but this is what the user wants so it's what I need to do. 
    Any help is greatly appreciated!! :)
    Thanks!
    Joni

    Finally got it to work.  I had to remove the first 5 characters from the replacement string (ŠŽšžŸ), couldn't find encoding that would handle these, and to be honest, I didn't really need them.  The important ones are still there, was probably
    just overkill on my part.
    UTF7 worked for the rest...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FileRdr As StreamReader = New StreamReader("m:\test\charReplace.txt", System.Text.Encoding.UTF7)
    Dim ReplaceWrtr As StreamWriter
    ReplaceWrtr = System.IO.File.CreateText("M:\test\CharReplaceOut.txt")
    Do While FileRdr.Peek() >= 0
    Dim currentRec As String = FileRdr.ReadLine
    removeAccent(currentRec)
    ReplaceWrtr.WriteLine(currentRec)
    Loop
    ReplaceWrtr.Close()
    End Sub
    'Replace foreign language characters with english characters
    Function removeAccent(ByRef myString As String)
    Dim A As String = "--"
    Dim B As String = "--"
    Const AccChars As String = "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    Const RegChars As String = "AAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    For i As Integer = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    myString = Replace(myString, A, B)
    Next
    removeAccent = myString
    End Function
    Thanks for all your help!  Greatly appreciated :)
    -Joni

  • How to read a text file and write text file

    Hello,
    I have a text file A look like this:
    0 0
    0 A B C
    1 B C D
    2 D G G
    10
    1 A R T
    2 T Y U
    3 G H J
    4 T H K
    20
    1 G H J
    2 G H J
    I want to always get rid of last letter and select only the first and last line and save it to another text file B. The output should like this
    0 A B
    2 D G
    1 A R
    4 T H
    1 G H
    2 G H
    I know how to read and write a text file, but how can I select the text when I am reading a text file. Can anyone give me an example?
    Thank you

    If the text file A look like that
    0 0
    0 3479563,41166 6756595,64723 78,31 1,#QNAN
    1 3479515,89803 6756588,20824 77,81 1,#QNAN
    2 3479502,91618 6756582,6984 77,94 1,#QNAN
    3 3479516,16334 6756507,11687 84,94 1,#QNAN
    4 3479519,14188 6756498,54413 85,67 1,#QNAN
    5 3479525,61721 6756493,89255 86,02 1,#QNAN
    6 3479649,5546 6756453,21824 89,57 1,#QNAN
    1 0
    0 3478762,36013 6755006,54907 54,8 1,#QNAN
    1 3478756,19538 6755078,16787 53,63 1,#QNAN
    2 0
    3 0
    N 0
    I want to read the line that before and after 1 0, 2 0, ...N 0 line to arraylist. I have programed the following code
    public ArrayList<String>save2;
    public BufferedWriter bufwriter;
    File writefile;
    String filepath, filecontent, read;
    String readStr = "" ;
    String[]temp = null;
    public String readfile(String path) {
    int i = 0;
    ArrayList<String> save = new ArrayList <String>();
    try {
    filepath = "D:\\thesis\\Material\\data\\CriticalNetwork\\test3.txt";
    File file = new File(filepath);
    FileReader fileread = new FileReader(file);
    BufferedReader bufread = new BufferedReader(fileread);
    this.read = null;
    // read text file and save each line content to arraylist
    while ((read = bufread.readLine()) != null ) {
    save.add(read);
    // split each arraylist[i] element by space and save it to String[]
    for(i=0; i< save.size();i++){
    this.temp = save.get(i).split(" ") ;
    // if String[] contain N 0 such as 0 0, 1 0, 2 0 then save its previous and next line from save arraylist to save2 arraylist
    if (temp.equals(i+"0")){
    this.save2.add(save.get(i));
    System.out.println(save2.get(i));
    } catch (Exception d) {
    System.out.println(d.getMessage());
    return readStr;
    My code has something wrong. It always printout null. Can anyone help me?
    Best Regards,
    Zhang

  • LabVIEW for ARM 2009 Read from text file bug

    Hello,
    If you use the read from text file vi for reading text files from a sdcard there is a bug when you select the option "read lines"
    you cannot select how many lines you want to read, it always reads the whole file, which cause a memory fault if you read big files!
    I fixed this in the code (but the software doesn't recognize a EOF anymore..) in CCGByteStreamFileSupport.c
    at row 709 the memory is allocated but it tries to allocate to much (since u only want to read lines).
    looking at the codes it looks like it supposed to allocated 256 for a string:
    Boolean bReadEntireLine = (linemode && (cnt == 0)); 
    if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;    //BUFINCR=256
    but cnt is never false since if you select read lines this is the size of the file!
    the variable linemode is also the size of the file.. STRANGE!
    my solution:
    Boolean bReadEntireLine = (linemode && (cnt > 0));  // ==
     if(bReadEntireLine) {    //if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;
    and now the read line option does work, and reads one line until he sees CR or LF or if the count of 256 is done.
    maybe the code is good but the data link of the vi's to the variables may be not, (cnt and linemode are the size of the file!)
    count should be the number of lines, like chars in char mode.
    linemode should be 0 or 1.
    Hope someone can fix this in the new version!
    greets,
    Wouter
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

    I have another solution, the EOF works with this one.
    the cnt is the bytes that are not read yet, so the first time it tries to read (and allocate 4 MB).
    you only want to say that if it's in line mode and cnt > 256 (BUFINCR) cnt = BUFINCR
    the next time cnt is the value of the bytes that are not read yet, so the old value minus the line (until CR LF) or if cnt (256) is reached.
    with this solution the program does not try to allocate the whole file but for the max of 256.
    in CCGByteStreamFileSupprt.c row 705
     if(linemode && (cnt>BUFINCR)){
       cnt = BUFINCR;
    don't use the count input when using the vi in line mode. count does not make sense, cnt will be the total file size. also the output will be an array.
    linemode seems to be the value of the file size but I checked this and it is just 0 or 1, so this is good
    update: damn it doesn't work!
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

  • Read from text file, display in textarea

    java newbie here - I'm trying to write a chat program that checks a text file every 1 second for new text, and then writes that text to a textArea. I've got the thread setup and running, and it checks and text file for new text - all that works and prints to system console - but I have no idea how to print that text to a textArea.
    I've tried textArea.append, but it seems this only works on the initial run - if I put it in the thread, it won't work. I can make textArea.append work if its in an ActionEvent - but how would I make an ActionEvent run only when my script detects new text from my text file?
    Any ideas on how to do this are appreciated.
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I've tried textArea.append, but it seems this only works on the initial
    run - if I put it in the thread, it won't work. I can make textArea.append
    work if its in an ActionEvent - but how would I make an ActionEvent
    run only when my script detects new text from my text file? ?
    It doesn't matter if you call the textArea.append() when the ActionEvent is triggered or if you call textArea.append() directly from a thread or any other object, the text will be append to te text area. What could have happen is you somehow lost the reference pointing to the textArea that you add to your user interface.
    example:
    JTextArea txtArea = blah..blah..blah
    MyThread t = new myThread(txtArea);
    class MyThread extends Thread{
        private JTextArea txtArea;
        public MyThread(Thread textArea){
            this.textArea = textArea;
        public void run(){
            textArea = new JTextArea(); // opps..you lost the reference to the textArea in the main gui...what you have done is created a new JTextArea object and point to tat..and this textarea object is not visible.
    }

Maybe you are looking for

  • A error message from running the jpa-cache-server.cmd file

    When I try to run jpa-cache-server.cmd file, it show the following error message: "failed to load main-class manifest attribute from %coherence_home%\lib\coherence-jpa.jar" What is the problem?

  • Computer reboots when I connect my iPod to a USB 2.0 slot

    Here are my specs: - I have the new iPod 60 GigaByte hardrive version. - Operating System on my PC: Windows XP - CPU: AMD Athalon XP 1.8 gHz - My PC is several years old and has four built-in USB 1.1 slots. My iPod works on all of these USB 1.1 ports

  • Code Contracts conflicts with custom SettingsProvider

    I'm using Code Contracts in my project (static & runtime), and I'm trying to implement a custom class derived from System.Configuration.SettingsProvider. From what I've gleaned on MSDN and various other sites, I need to override the Initialize() meth

  • How to ImplementCross validation rules in OA Page

    I have created a custom page which has a Key flex field.How do i implement the cross validation rules?Please let me know.Thanks in advance

  • FM Transmitter thinks I have a USB cable plugged i...

    I have owned my N900 for just about 24hrs now and love it.... minus this new problem.   I went to use the FM Transmitter on the way home today and it said " can not use FM Transmitter while USB cable is plugged in"  I do not have a cable plugged in.