-1

I am having trouble getting my java program to read any text files.

public static void main(String[] args) throws java.io.IOException {

        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        try {
            long base = Long.parseLong(args[0]);

            String input = br.readLine(); //read first line till the end of file

            long list = Long.parseLong(input);

            convertBase(base, list);
        }
        finally {
            br.close();
        }
}

The program works when I manually type the values into the command line, but when I try to use a text file it throws exceptions:

Exception in thread "main" java.lang.NumberFormatException: For input string: "baseconverion.txt"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at FromDecimal.main(FromDecimal.java:46)

Not sure what I am doing wrong/missing.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • You should print `input` before trying to process it - you might be surprised about its content. – Nir Alfasi Oct 12 '17 at 23:56
  • 1
    You are trying to parse a filename as a `long`. Solution: don't. NB `readLine()` doesn't 'read first line till the end of file'. Why are you trying to parse a text file as `longs` in the first place? – user207421 Oct 12 '17 at 23:56
  • I need to parse to longs because I have another method where I convert decimal number to base – Sookie Sookie Oct 12 '17 at 23:59
  • Parsing to longs converts to *binary*, not decimal, but you don't have any requirement to parse the *filename* as a long. You have your inputs and arguments mixed up somehow. NB There is exactly nothing here that reads a text file. – user207421 Oct 13 '17 at 00:00

1 Answers1

0

when I try to use a text file

You mean 'when I enter a filename instead of a number'. You aren't 'try[ing]' to use a text file' at all. All you're doing is entering a filename at the console. There is nothing here that opens or reads a text file whatsoever. Java is not magic: it won't magically realize that's a filename and magically open it for you.

You need to read about file I/O in the Java Tutorial and the Javadoc.

You also shouldn't be using Long.parseLong() if your objective is to convert decimal into another base. You need to pass the original line to your conversion method.

user207421
  • 305,947
  • 44
  • 307
  • 483