V
V
Viktor Zorin2017-11-01 20:41:04
Java
Viktor Zorin, 2017-11-01 20:41:04

Entering data from a Java text document, can it be simplified somehow?

Beginner Java programmer. Faced a situation when it is necessary to take the data from a text file. In this case, the file contains an integer 10. When I tried to read from the file, I got 48 and 47. Why this happens, I still have not figured out. I noticed that if these numbers are converted to char, then it displays what I need. As a result, to get the integer 10 that was in the file, I had to convert the value several times:

import java.io.*;

public class Test {

  public static void main(String[] args) throws IOException{
    FileInputStream reader = new FileInputStream("D:\\Eclipse\\workspace\\MyExperimentalProject\\files\\input.txt");
    int a = 0;
    String result = "";
    
    while (true) {
      a = reader.read();
      if (a == -1) {
        break;
      }
      result = result + (char)a;
    }
    System.out.println(result); //для сравнения результата
    Integer intresult = new Integer(result);
    intresult++;//убеждаюсь в том, что это всё-таки число
    System.out.println(intresult);
}
}

I achieved what I wanted, but it seems to me that I chose the most difficult of all paths. Experienced programmers, please tell me if it is possible to make this process simpler, and if so, how?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zakharov Alexander, 2017-11-01
@AlexZaharow

You have in the file not the number 10, but the string "10". Here is a conversion example: https://stackoverflow.com/questions/5585779/how-to...
How to parse a string into tokens is a separate task. You can manually, you can use regular expressions.
Look at the table of ASCII codes, find the codes for the characters 1 and 0 there and it will become clear.

D
Dmitry Alexandrov, 2017-11-01
@jamakasi666

I'll give you a little hint:
1) Be sure to be sure which encoding is in the file and which one you are reading.
2) The string is easy to split, for example, so to start with String[] arr = "unknown string with the number 100 and 72".split(" ");
3) Then you can go on the forehead, but this is not entirely good, like this Integer.parseInt( String str ), other primitive types have the same methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question