PrintWriter not working, but PrintStream is - output

I'm trying to print some characters to an output file. If I do:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
out.println("Hi");
nothing happens.
However, if I do:
PrintStream out = new PrintStream(new File("test.txt"));
out.println("Hi");
the appropriate message is printed and visible in the test.txt file. I'm wondering why this is happening??

Related

Servlet doesnt write JSON Output to AJAX

Following code for my output:
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
ToJson obj = new ToJson();
String obj1 = objectMapper.writeValueAsString(obj);
response.setContentType("application/json");
out.print(obj1);
System.out.println(obj1);
out.close();
The obj1 looks like this: {"prname1":"P1neu","anz1":"342356","prid1":"1","price1":"25"}
It should send the string out so I can parse it in my AJAX and display it but somwhow it ends up with nothing as console.log/etc doesnt display any data.
I had out.append but it also didnt work.
Use below code to send response as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(obj1);
Please check this How to use Servlets and Ajax?
It will surely help you.

Superscript characters are resulting in to junk characters in generated CSV file when using ICsvListWriter

I am trying to write superscript characters in .csv file. I am using method write(List<?> columns)of org.supercsv.io.ICsvListWriter. In generated .csv file the superscript character is coming along with junk character before it.
List columns = new ArrayList();
String myString = "abcd1";
columns.add(myString.replaceAll("1", "¹"));
csvWriter.write(columns);
In the generated .csv file it is coming as
abcd¹
I also tried with unicode but it is not helping.
columns.add(myString.replaceAll("1", "\u00B9"));
Any suggestion here please?
Found a solution for this problem. Correction was needed in creating ICsvListWriter object. Previously I was having this code where 'response' is HttpServletResponse.
CsvPreference preference = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).useEncoder(new DefaultCsvEncoder()).build();
ICsvListWriter csvWriter = new CsvListWriter(response.getWriter(), preference);
This code is enhanced to this:
ServletOutputStream output = response.getOutputStream();
output.write(new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF });
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"));
CsvPreference preference = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).useEncoder(new DefaultCsvEncoder()).build();
ICsvListWriter csvWriter = new CsvListWriter(writer, preference);
This fixed the issue and all of the superscript characters are now coming properly in generated CSV file without any junk characters. No mater whether I use actual superscript characters or their Unicode, this fix works.

GSON: converting a .json file to a JsonObject

Of course, for this i used JsonParser, Here is my Code:
JsonParser parser = new JsonParser();
Object object = parser.parse(new FileReader("c:\\Projects\\elastic-search-single-log-result.json"));
JsonObject jobject = (JsonObject) object;
String message = jobject.get("msg").toString();
return message;
However, the msg is a stack trace enclosed by triple quotes, and it gives me a Malformed Json Exception, at the second line shown above.
I saw stuff about JsonReader having a getLenientMethod, I was wondering if there was something similar for this.
I fixed it --- I simply had to remove the triple quotes, and I get the JSON file from kibana (which formatted the stack trace a little differently). I hope this helps anyone in the future who will have the same problem

Read text from webpage without html

I'm trying to extract the text of an url using WebClient in C#.
But the content contains html tags and I only want raw text.
My code is as follows:
string webURL = "https://myurl.com";
WebClient wc = new WebClient();
byte[] rawByteArray = wc.DownloadData(webURL);
string webContent = Encoding.UTF8.GetString(rawByteArray);
I get the following error with the above code:
'The remote server returned an error: (403) Forbidden.
and change my code to:
string webURL = "https://myurl.com";
WebClient wc = new WebClient();
wc.Headers.Add("user-agent", "Only a Header!");
byte[] rawByteArray = wc.DownloadData(webURL);
string webContent = Encoding.UTF8.GetString(rawByteArray);
The above code has no error, but the result contains html tags. html tags can be removed using Regex:
var result= Regex.Replace(webContent, "<.*?>", String.Empty);
But this method is not accurate and does not good performance. Is there a better way to extract just the text without the html tags from an url?
The Navigate function doesn't block execution. You need to register for the DocumentCompleted event, then you should be able to grab the contents within that.
It's not the way you're using that. First of all you should know you have to use Web Client
Now you can try this code :
WebClient client = new WebClient();
string content = client.DownloadString("https://stackoverflow.com/search?q=web+browser+c%23");

trying to append to a json file

I want to save some data about tweets in a persistent json file. I'm using org.codehaus.jackson.JsonGenerator to write the tweets to a file, which works fine when they are inserted all at once. My code:
JsonGenerator g = new JsonFactory().createJsonGenerator(jsonFile, JsonEncoding.UTF8);
for(Tweet t : list){
g.writeStartObject();
g.writeStringField(ID_FIELD, t.getTweetID());
g.writeStringField(DATE_FIELD, dateFormat.format(t.getDate()));
if(t.isRetweet())
g.writeStringField(RETWEET_FIELD, t.getOriginalTweet());
g.writeArrayFieldStart(HASHTAG_FIELD);
for(String s : t.getHashtags())
g.writeString(s);
g.writeEndArray();
g.writeEndObject();
}
g.close();
Problem is, if I want to add another bunch of tweets to the same file, this function will overwrite the previous ones. I've been trying to keep the generator open instead of closing it every time, but it screwed up the process of writing in the first place. also, the API doesn't suggest any way of "continuing where I left off". No luck with other json streamers either so far. Suggestions?
Not sure if I understand correctly, but if the problem is that you can't append multiple JSON objects to your output - then just open a FileWriter and make sure that the target isn't auto-closed after each object write.
For instance:
FileWriter output = new FileWriter("/path/to/file");
ObjectWriter jsonWriter = new ObjectMapper()
.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false)
.writer();
jsonWriter.writeValue(output, object1); output.write('\n');
jsonWriter.writeValue(output, object2); output.write('\n');
jsonWriter.writeValue(output, object3); output.write('\n');