I have a method readFromFile like this:  private static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; readFromFile(String name) { ArrayList&lt;ArrayList&lt;Integer&gt;&gt; inputs = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();  try {     InputStream in = ReadWriteFile.class.getClass().getResourceAsStream(name);     BufferedReader reader = new BufferedReader(new InputStreamReader(in));     String line;      while ((line = reader.readLine()) != null) {         ArrayList&lt;Integer&gt; input = new ArrayList&lt;Integer&gt;();          for (int i=0; i&lt;line.length(); i++) {             int value = 0;             try {                 value = Integer.parseInt(String.valueOf(line.charAt(i)));             } catch (Exception e) {                 input.add(value);             }         inputs.add(input);         }     reader.close();     } } catch (IOException e) {     e.printStackTrace(); } return inputs; }   and I use this method here to read a folder of txt files. I need it to put the names of files in an arraylist (the files are an alphabet):  public static ArrayList&lt;TrainingSet&gt; readTrainingSets() { ArrayList&lt;TrainingSet&gt; trainingSets = new ArrayList&lt;TrainingSet&gt;();  for (int i=0; i&lt;26; i++) {     char letterValue = (char) (i+26);     String letter = String.valueOf(letterValue);      for (ArrayList&lt;Integer&gt; list : readFromFile("C:\\Users\\hp\\Desktop\\resources\\" + letter + ".txt")) {         trainingSets.add(new TrainingSet(list, GoodOutputs.getInstance().getGoodOutput(letter)));     } } return trainingSets; }   The source folder includes files like: A.txt, B.txt, etc. When I try to run the code I get an error.   Exception in thread "main" java.lang.NullPointerException at java.io.Reader.&lt;init&gt;(Unknown Source) at java.io.InputStreamReader.&lt;init&gt;(Unknown Source) at data.ReadWriteFile.readFromFile(ReadWriteFile.java:34) at data.ReadWriteFile.readTrainingSets(ReadWriteFile.java:22) at network.Train.&lt;init&gt;(Train.java:16) at gui.MainGui.&lt;init&gt;(MainGui.java:38) at gui.MainGui.main(MainGui.java:32)   I guess the method can't find the files on my computer. But I don't know why. Is the form wrong? Can you help me?
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
46689
I'm reading source code of the linux tool . They use the read() function there. Is there a difference to the standard C fread() function? (I'm not counting the arguments as a difference.)
282
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version. Is there a simpler way than: List&lt;String&gt; newList = new ArrayList&lt;String&gt;(); newList.addAll(listOne); newList.addAll(listTwo);
56415
I have four foreach loops that iterate through the collections and based on a condition do something.   Here is the code that I am writing now:  boolean breakFlag = false; String valueFromObj2 = null; String valueFromObj4 = null; for(Object1 object1: objects){   for(Object2 object2: object1){     // I get some value from object2     valueFromObj2 = object2.getSomeValue();     for(Object3 object3 : object2){       for(Object4 object4: object3){        // Finally I get some value from Object4.        valueFromObj4 = object4.getSomeValue();        // Compare with valueFromObj2 to decide either to break all the foreach loop        breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );        if(breakFlag){break;}       } // fourth loop ends here       if(breakFlag){break;}     } // third loop ends here     if(breakFlag){break;}   } // second loop ends here   if(breakFlag){break;} } // first loop ends here   The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack&nbsp;Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable.
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
25016
I am getting the following error trying to read from a socket. I'm doing a readInt() on that InputStream, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.  I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?    I do note that I have the following line:  socket.setSoTimeout(10000);   just prior to the readInt(). There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.  Anyway, just mentioning it, hopefully not a red herring. :-(
80627
I have a string variable that represents the name of a custom class. Example:   string s = "Customer";   I will need to create an arraylist of customers. So, the syntax needed is:  List&lt;Customer&gt; cust = new ..    How do I convert the string s to be able to create this arraylist on runtime?
60121
This is what my JSON looks like: {"series":[{,"points":[{"ts":"1473850836254","value":"11.27"},{"ts":"1473851256637","value":"6.44"}]}]}  I am trying to access the values in "points" by calling something like: data.series.points[0].ts       Void Start(){     IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text);     print("Series point length" + data.series.points.Count);     print("Series point 0" + data.series.points.get_Item[0].ts); // error     }   //----------------------------------------- classes -------------------------      [System.Serializable]     public class IncomingData     {         public Series series;         public static IncomingData CreateFromJSON(string json)         {                return JsonUtility.FromJson&lt;IncomingData&gt;(json);          }     }      [System.Serializable]     public class Series     {         public List&lt;Points&gt; points = new List&lt;Points&gt; { };     }       [System.Serializable]     public class Points     {         public int ts;         public int value;     }   My error:  // error CS0021: Cannot apply indexing with [] to an expression of type `method group'
1685
Consider:  List&lt;String&gt; someList = new ArrayList&lt;String&gt;(); // add "monkey", "donkey", "skeleton key" to someList     for (String item : someList) {     System.out.println(item); }   What would the equivalent for loop look like without using the for each syntax?
8293
Possible Duplicate:          Using \input{filename}, I can input a file canned "filename.tex". I have a directory containing all of the files I want to include. How can I create a for loop, which inputs all of those files?   The contents of the directory sometimes changes (so I do not want to manually specify all of the files). The files are numbered (e.g. file01.tex, file02.tex), so the loop should have no difficulty inputing them in the correct order. Other code will be placed within the for loop (before and after the input command), so I do not want to simply list all of the files at once (e.g. \input{file01,file02}).
54645
In the Java snippet:  SyndFeedInput fr = new SyndFeedInput(); SyndFeed sf = fr.build(new XmlReader(myInputStream)); List&lt;SyndEntry&gt; entries = sf.getEntries();   the last line generates the warning   "The expression of type List needs unchecked conversion to conform to List&lt;SyndEntry&gt;"  What's an appropriate way to fix this?
6108
Why do I get compiler errors with this Java code?  1  public List&lt;? extends Foo&gt; getFoos() 2  { 3    List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;(); 4    foos.add(new SubFoo()); 5    return foos; 6  }  Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.  Errors I get with this code:   On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;" On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"   Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();".  But I'm still having the issue with Line 4.
2343
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.  Is there a better/different way to read a file into a string in Java?  private String readFile(String file) throws IOException {     BufferedReader reader = new BufferedReader(new FileReader (file));     String         line = null;     StringBuilder  stringBuilder = new StringBuilder();     String         ls = System.getProperty("line.separator");      try {         while((line = reader.readLine()) != null) {             stringBuilder.append(line);             stringBuilder.append(ls);         }          return stringBuilder.toString();     } finally {         reader.close();     } }
26601
Is there a Java equivalent for  in C#/.NET? Or any code to accomplish this?  This static method combines one or more strings into a path.
18961
I have the following code:   DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);   How can I get it to parse XML contained within a String instead of a file?
63512
Am not doing anything fancy, just trying to use  method of list.      List&lt;Id&gt; myIdList = new List&lt;Id&gt;(); myIdList.add('0060E000008PdMk');  Id oppId ='0060E000008PdMk';      System.debug(myIdList.contains(oppId)); //Returns false   To my surprise, I spent a few hours debugging and came with this problematic code. Are we not supposed to use contains for List&lt;Id&gt; ?  Changing the type from List&lt;Id&gt; to List&lt;String&gt; makes my code run, but I dont have any clue why it does?   Can anyone shed some light?  UPDATE : As per the suggestion of sfdcfox I have raised a case with SF support. Case number "19522568". I will keep you guys updated with the results.  UPDATE 2 : Salesforce reached out to me for this,   A bug W-4884673 already exist for this issue. SF R&amp;D team is working on the same. Known issue link for reference:   There isn't any ETA for this to be fixed, so the case will be closed as "bug fix submitted"  UPDATE 3 : This has now been resolved
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?