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.
stringArrayToIntArray(). Most likely you need to look atcom.company.Main.main()- tutankhamun