In the txt file there are numbers separated by spaces. readFile (File file) - returns a valid array of strings containing numbers. When trying to convert an array of strings to an array of integers, a NumberFormatException . And all the elements are normal, except for the last one. Listing:

 public class GetDataFromFile extends GetData { public String getStandartPath() { return standartPath; } private String standartPath = "\\dataForExample\\example.txt"; public String[] readFile(File file) throws IOException { FileReader fileReader = null; CharArrayWriter charArrayWriter = null; StringWriter stringWriter = null; char[] buffer = new char[1024]; try{ fileReader = new FileReader(file); charArrayWriter = new CharArrayWriter(); int count; while ((count=fileReader.read(buffer))!= -1){ charArrayWriter.append(new String(buffer)); } }catch (IOException ex) { throw new IOException(""+ex); } finally { fileReader.close(); charArrayWriter.close(); } return charArrayWriter.toString().split(" "); } public static int[] stringArrayToIntArray(String[] strings){ int[] ints = new int[strings.length]; for (int i = 0; i<ints.length; i++){ try { ints[i] = Integer.parseInt(strings[i]);// same result for "new Integer(str) and Integer.valueOf(str) } catch (NumberFormatException e) { throw new NumberFormatException("Error format in element "+ i + e); } } return ints; } } 

Actually log:

Exception in thread "java.lang.NumberFormatException": Error format in element 23java.lang.NumberFormatException: For input string: "11
"at com.company.Data.GetDataFromFile.stringArrayToIntArray (GetDataFromFile.java:50) at com.company.Main.main (Main.java:25) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect. NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang. .application.AppMain.main (AppMain.java:140)

Thank you in advance for your help.

  • @Saidolim Djuraev From the point of view of semantics, the log in the form of a quote is certainly more correct, but the preformat looks better - tutankhamun
  • Show what happens before calling stringArrayToIntArray() . Most likely you need to look at com.company.Main.main() - tutankhamun

1 answer 1

In the log, this is the place:

For input string: "11"

says that the parser is not able to deal with spaces.

I recommend using the trim() method before calling parseInt() .

  • Rather, at the end of the line is \n . - VladD
  • @VladD There are many of them - tutankhamun
  • @tutankhamun, thank you, add trim (), everything works. - Alexey Semenov