does bufferedWriter require getters - java

Hi i know the use of getters is to restrict access. The issue is i have a buffered writer that is using some information in another class. Therefore using getters i have gotten that information and written into a file using the bufferedWriter.
The issue comes when i am trying to use some information in the same class as the bufferedWriter. It doesnt write those details . Shows no error in the code either just doesnt write it. If the data is in the same class as the buffered writer i assume that it doesnt need to be accessed using getters? although the values are stored in another method. Explain this
Thank you alot
bufWrite.write("Your Character Class:" + character_Class + "\n");
bufWrite.write("Your Character Level:" + level + "\n");
The character class and level here are from 1 class called character. To access these information i have used getters (Since the buffered writer is inside another class.Basically i have 3 classes. Character details in one and i am using the bufferedWriter which is in a different class to store these details into a file.)
These details are written into the file completely.
for(Object o:skillInfo){
bufWrite.write("" + o + "- Rank(skill Points) :" + rank);
}
i am trying to use this foreach loop to write stuff inside a linkedlist. This linked list is inside the same class as the buffered writer statements are. But this doesnt get written while the other details(as listed above) get written. The only difference is that those details are using getters since they are not in the same class as the bufferedWriter is while the linked list is in the same as the bufferedWriter thus doesnt use a getter.
I hope this is clear enough
**Update
Also please note that the character.Level and the rank are user entered values.

To answer your question, a BufferedWriter by itself does not 'require' getters.
If your BufferedWriter is not writing data, then the problem might be how you are actually writing the data. You also might want to check if you are calling .close() when you are done writing the data.
Another problem might be how your data is returned from the get-er.
Your question is rather ambiguous, so any answer can only be a guess. I recommend reading up on how to make a good question, so that people can provide better answers.
https://stackoverflow.com/help/how-to-ask
https://stackoverflow.com/help/mcve
*Edit:
Thank you for updating your question.
If you want to write out the details of character_Class, you do need to call the getters of the specific information that you want to get from the class.
The reason why bufWrite.write("Your Character Class:" + character_Class + "\n"); doesn't throw an exception or crash is because of how java coerces classes to String.
The line of code:
"Your Character Class:" + character_Class
is the same as:
"Your Character Class:" + character_Class.toString()
Same happens with objects from skillInfo:
bufWrite.write("" + o.toString() + "- Rank(skill Points) :" + rank);
Basically, if you concatenate '+' a String and an object, it calls toString() on the object. If you concatenate a String and a primitive type, it just converts them to Strings first.

Related

Convert string into utf-8 in php

There is a script written in Java and I am trying to convert it into PHP, but I'm not getting the same output.
How can I get it in PHP same as in Java?
Script written in Java
String key = "hghBGJH/gjhgRGB+rfr4654FeVw12y86GHJGHbnhgnh+J+15F56H";
byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
Output: [B#167cf4d
Script written in PHP
$secret_key = "hghBGJH/gjhgRGB+rfr4654FeVw12y86GHJGHbnhgnh+J+15F56H";
utf8_encode("AWS4".$secret_key);
Output: AWS4hghBGJH/gjhgRGB+rfr4654FeVw12y86GHJGHbnhgnh+J+15F56H
The result [B#167cf4d you are getting is a toString() call on the byte array. The [B means the value is a byte array. #167cf4d is it's location within the virtual memory. You simply cannot get the PHP script to give you the same result. What you need to do is fix the printing on the Java side, but we don't know what API you're using to print it and where. Is it a web-application, a local application, etc... ?
edit:
Since you're using it in a Java web-application, there are two likely scenarios. The code is either in a Servlet, or in a JSP. If it's in a servlet, you have to set your output to UTF-8, then you can simply print the string like so:
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write("AWS4");
out.write(key);
If it's in a JSP, that makes it a bit more inconvenient, because you have to make sure you don't leave white-spaces like new lines before the printing begins. It's not a problem for regular HTML pages, but it's a problem if you need precisely formatted output to the last byte. The response and out objects exist readily there. You will likely have some <%#page tags with attributes there, so you have to make sure you're opening the next one as you're closing the last. Also a new line on the end of file could skew the result, so in general, JSP is not recommended for white-space-sensitive data output.
You can't sysout an byte array without converting it to a string, UTF-8 by default, toString() is being called,when you do something like:
System.out.println("Weird output: " + byteArray);
This will output the garbage you mentioned above. Instead, create a new instance of the standard String class.
System.out.println("UTF-8: " + new String(byteArray));
In Java you get the object reference of the byte array, not its value. Try:
new String(kSecret, "UTF-8");

ArrayList and Formatter not behaving as expected

I have two Arraylists, one contains an entire list of objects, the second contains objects to remove from the first list.
When I remove the objects from the first list and when I output those objects to a file using a Formatter, nothing is written to the file. However if I output the objects from the first Arraylist, without removing any objects, all of those objects appear in the file.
For example:-
for(Invoice inv : tempStore)
{
if(invoiceLines.contains(inv))invoiceLines.remove(inv);
}
//for each invoice in the ArrayList
for(Invoice invoice : invoiceLines)
{
output.format("%"+this.spec.getLength("XXXX")+"s\t",checkString(invoice.getInvoiceDate()));}
gives me no output, however doing just:-
//for each invoice in the ArrayList
for(Invoice invoice : invoiceLines)
{
output.format("%"+this.spec.getLength("XXXX")+"s\t",checkString(invoice.getInvoiceDate()));}
gives me output information, when manually debugging the application the arraylist (the one with the objects removed), does contain objects still and those objects contain the correct values. It's almost as if the Arraylist, once objects are removed is losing the pointers in memory.
Any ideas? Unfortunately I can't give much in the way of specific code, however ask any questions and I will try to answer as best as I can. The language is Java and I'm using Java compliance 1.5 in the SDK.
To identify the error you can add more output (as console output or using a Logger) on the removing operation:
System.out.println("Items before removal: " + invoiceLines.size());
for(Invoice inv : tempStore)
{
if(invoiceLines.contains(inv)) {
invoiceLines.remove(inv);
System.out.println("removed " + inv + ". Items left: " + invoiceLines.size());
}
}
If there are more than items removed during one iteration, you want to check the equals() and hashCode() Implementation of the Invoice class.
If you have your own implementation, make sure you followed the Object.equals()-Contract.
Formatter.flush() and Formatter.close() need to be called at the end of output.

Produce Java literal syntax for arbitarary object in Java

I'm writing a tool to fill an arbitrary Java value object with arbitrary values, output the content in JSON, and output a list of assertions that can be pasted into a unit test.
At the core of this is:
final Method getter = object.getClass().getMethod(getterName, new Class<?>[0] );
System.out.println("assertEquals("
+ getter.invoke(object)
+ ", actual."
+ getter.getName() +
"());");
This outputs lines like:
assertEquals(42, actual.getIntegerValue());
assertEquals(foo, actual.getStringValue());
assertEquals([B#5ae80842, actual.getByteArrayValue());
Note that the string value is not properly quoted, and the byte array is not a Java byte array literal. I can improve this with a method to format the object depending on its type:
... + formatAsLiteral(getter.invoke(object)) ...
static String formatAsLiteral(Object obj) {
if(obj instanceof String) {
return "\"" + obj + "\"";
} else {
return obj.toString();
}
}
But I want to support as many standard types as is practical - including arrays and possibly collections.
Is there a better way, than to add an if() for every type I can think of?
Is there a better way, than to add an if() for every type I can think of?
Here are a few alternatives:
A dispatch table
A callback system works by storing event handlers in an array. When the underlying event is detected the dispatch system loops through the array calling the callback functions in turn.
A lexical scanner
The Lexer class, below, streamlines the task of matching of regular-expression against the input, as well as that of producing Token objects that precisely describe the matched string and its location within the input stream.
A parser generator
The framework generates tree-walker classes using an extended version of the visitor design pattern which enables the implementation of actions on the nodes of the abstract syntax tree using inheritance.
References
Understanding Dean Edwards' addevent JavaScript
A simple lexical scanner in Java
Open Source Parser Generators in Java

Java concatenate to build string or format

I'm writing a MUD (text based game) at the moment using java. One of the major aspects of a MUD is formatting strings and sending it back to the user. How would this best be accomplished?
Say I wanted to send the following string:
You say to Someone "Hello!" - where "Someone", "say" and "Hello!" are all variables. Which would be best performance wise?
"You " + verb + " to " + user + " \"" + text + "\""
or
String.format("You %1$s to %2$s \"%3$s\"", verb, user, text)
or some other option?
I'm not sure which is going to be easier to use in the end (which is important because it'll be everywhere), but I'm thinking about it at this point because concatenating with +'s is getting a bit confusing with some of the bigger lines. I feel that using StringBuilder in this case will simply make it even less readable.
Any suggestion here?
If the strings are built using a single concatenation expression; e.g.
String s = "You " + verb + " to " + user + " \"" + text + "\"";
then this is more or less equivalent to the more long winded:
StringBuilder sb = new StringBuilder();
sb.append("You");
sb.append(verb);
sb.append(" to ");
sb.append(user);
sb.append(" \"");
sb.append(text );
sb.append('"');
String s = sb.toString();
In fact, a classic Java compiler will compile the former into the latter ... almost. In Java 9, they implemented JEP 280 which replaces the sequence of constructor and method calls in the bytecodes with a single invokedynamic bytecode. The runtime system then optimizes this1.
The efficiency issues arise when you start creating intermediate strings, or building strings using += and so on. At that point, StringBuilder becomes more efficient because you reduce the number of intermediate strings that get created and then thrown away.
Now when you use String.format(), it should be using a StringBuilder under the hood. However, format also has to parse the format String each time you make the call, and that is an overhead you don't have if you do the string building optimally.
Having said this, My Advice would be to write the code in the way that is most readable. Only worry about the most efficient way to build strings if profiling tells you that this is a real performance concern. (Right now, you are spending time thinking about ways to address a performance issue that may turn out to be insignificant or irrelevant.)
Another answer mentions that using a format string may simplify support for multiple languages. This is true, though there are limits as to what you can do with respect to such things as plurals, genders, and so on.
1 - As a consequence, hand optimization as per the example above might actually have negative consequences, for Java 9 or later. But this is a risk you take whenever you micro-optimize.
I think that concatenation with + is more readable than using String.format.
String.format is good when you need to format number and dates.
Concateneting with plus, the compilet can transforms the code in performatic way. With string format i don t know.
I prefer cocatenation with plus, i think that is easer to undersand.
The key to keeping it simple is to never look at it. Here is what I mean:
Joiner join = Joiner.on(" ");
public void constructMessage(StringBuilder sb, Iterable<String> words) {
join.appendTo(sb, words);
}
I'm using the Guava Joiner class to make readability a non-issue. What could be clearer than "join"? All the nasty bits regarding concatenation are nicely hidden away. By using Iterable, I can use this method with all sorts of data structures, Lists being the most obvious.
Here is an example of a call using a Guava ImmutableList (which is more efficient than a regular list, since any methods that modify the list just throw exceptions, and correctly represents the fact that constructMessage() cannot change the list of words, just consume it):
StringBuilder outputMessage = new StringBuilder();
constructMessage(outputMessage,
new ImmutableList.Builder<String>()
.add("You", verb, "to", user, "\"", text, "\"")
.build());
I will be honest and suggest that you take the first one if you want less typing, or the latter one if you are looking for a more C-style way of doing it.
I sat here for a minute or two pondering the idea of what could be a problem, but I think it comes down to how much you want to type.
Anyone else have an idea?
Assuming you are going to reuse base strings often Store your templates like
String mystring = "You $1 to $2 \"$3\""
Then just get a copy and do a replace $X with what you want.
This would work really well for a resource file too.
I think String.format looks cleaner.
However you can use StringBuilder and use append function to create the string you want
The best, performance-wise, would probably be to use a StringBuffer.

How to read a simple xpm image and display it using Java?

I am assigned a task to build a simple xpm image viewer. I can't use any existing toolkit library for this.
I know that xpm images are string array like this ( I can write one) -
/* XPM */
static const char *const hi[] = {
"7 5 2 1",
" c black",
". c yellow",
".. ..",
". . . .",
". . .",
". .",
". ."
};
I want to use java for this. My question is -
1. How to make a String variable (hi[]) from this xpm file so that I can use it in my main class?
2. Good way to display it in a GUI?
3. Any other dictation...
Many thanks for your help
You'll have to firstly write a parser - a program/method/class/whatever that reads this file line-wise and extract the necessary data.
BufferedReader r =
new BufferedReader(new InputStreamReader(new FileInputStream(file),
"US-ASCII"));
gives you a BufferedReader, which has a readLine() method.
The first some lines you throw away or handle specially, and then the main bunch of lines are the real image data. There you throw away the quotes and commas, and have the plain data in string form.
To put it in a image, look at the classes in java.awt.image - specially BufferedImage and the classes used by it (Raster/WriteableRaster, IndexColorModel).
Instead, you could also simply hold the data in your String[] form, and in the paint-method of a custom component access the individual pixels. This would be a bit slower, I think.
Don't know if this will work for you: http://www.bolthole.com/java/Xpm.html , but I reckon once it is converted into a Java image, you should able to do whatever you want in Java.

Categories