How to return the value of a string with a space

How can I change my main class to get values โ€‹โ€‹without losing spaces?

Here is part of my main class:

StringBuilder sb = new StringBuilder(); Scanner s = new Scanner(new FileReader(new File("C:/User/waithaka/Documents//duka.json"))); while (s.hasNext()) { sb.append(s.next()); } s.close(); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); String jstring = sb.toString(); Result results = gson.fromJson(jstring, Result.class); List<data> dat = response.getData(); for (data data : dat) { System.out.println("The item is " + data.getItem()); } 

The last line prints the values โ€‹โ€‹without spaces. For example, a value with the string "Black and yellow" will be changed to "Blackandyellow" . "Blackandyellow"

+5
source share
2 answers

I think your problem comes from using Scanner, as it could be trimming spaces. Since you already use some Google libraries (Gson), I would also use Google guava, its Files class has a toString () method that will read the whole file in String:

Files.toString ()

+2
source

If you look at the Scanner.java class, you can see spaces that are treated as newline characters.

 public Scanner(InputStream source) { this(new InputStreamReader(source), WHITESPACE_PATTERN); } 

You need to set the line separator as

 s.useDelimiter(System.getProperty("line.separator")); 

I was able to replicate and fix the problem, below is the code -

Json

 { name:"Stack-overflow", url:"http://www.stack-overflow .com" } 

And here is the class

 public class GsonTest { public static void main(String[] args) throws FileNotFoundException { StringBuilder sb = new StringBuilder(); Scanner s = new Scanner(new FileReader(new File( "/Users/chatar/Documents/dev/projects/stack-overflow/stack-overflow/bin/C:/User/waithaka/Documents/duka.json"))); s.useDelimiter(System.getProperty("line.separator")); while (s.hasNext()) { String nxt = s.next(); sb.append(nxt); } s.close(); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); String jstring = sb.toString(); Result results = gson.fromJson(jstring, Result.class); System.out.println("The item is " + results); } } 
+3
source

All Articles