Before that sorry for my bad english because it's not my first language.
Excuse me, i'm trying to convert array byte to string in error handling try catch java. And if user input integers, the result will be +2. I've tried but always error, i hope someone can help me.
Here's my code:
package exception;
public class TugasTiga {
public static void main (String [] args) {
byte[] b = new byte[5];
System.out.println("Input bilangan bulat: ");
try { System.in.read(b);
} catch (java.io.IOException e);
int N = Integer.valueOf(b).intValue();
System.out.println("Hasil: " + (N+2));
}
}
To convert a byte[] to String use s=new String(bytes,"UTF-8") or whatever encoding has been used.
However I assume that you misunderstood how the console works because you asked for a conversion to string but you need integer. We normally use the Scanner class to read interactive input and convert it.
Take a look at this tutorial, which explains how to use the scanner class: https://www.w3schools.com/java/java_user_input.asp
Just like that:
byte[] bytes = new byte[5];
String stringFromByteArray = new String(bytes);
Here's the solution:
byte[] bytes = new byte[5]; //create the list
String finalS = ""; //create the string
for(byte element : bytes) { //for all elements in the list
finalS += Byte.toString(element); //add to the string "finalS" the byte converted to string
}
EXAMPLE: if the 5 bytes are {1,2,3,4,5}, the string is "12345"
Related
public static void main(String[] args) throws Exception {
File inputFile = new File("input.txt");
Scanner read = new Scanner(inputFile);
File outputFile = new File("output.txt");
PrintWriter print = new PrintWriter(outputFile);
if (!inputFile.exists()) {
System.out.println("File does not exist!");
}
ArrayList<Event> myArray = new ArrayList<>();
String commands="";
while (read.hasNext()) {
if(commands.matches("AddMovie")){
addMovie(read);
}
}
print.flush();
print.close();
read.close();
}
//java netbeans
public static Event addMovie(Scanner in){
String m[]=new String[6];
for (int i = 0; i < m.length; i++) {
String name=in.next();
Date sDate=new Date(in.next());
Date eDate=new Date(in.next());
double price=in.nextDouble();
String city=in.next();
String address=in.next();
String language=in.next();
String tAudience=in.next();
double raiting=in.nextDouble();
int tickets=in.nextInt();
}
return movie;}
well I am having a problem here so my program must read from a file these given data
AddMovie--The Upside, 6/3/2019, 6/6/2019, 50, Riyadh, Al Qasr Mall, English, Family, 4.5, 40, Comedy, Nicole Kidman, F, 1967
I have to store them in an ArrayList of object and I have to use non-word characters as a delimiter to split these data should I make a method and inside this method a 1-dimensional array and then use split() method?
From what I can understand you are on the right track. Given you read the data you have provided as one single string, you can use the split(",") method on it and store the result of that into an array of strings.
I think that splitting on 'non-word characters' would not be a good idea, as for example you would not want 4.5 to be split into 4 and 5.
I would probably split on ','.
If you were worried about efficiency, it would be a good idea to create a java.util.regex.Pattern object with (for e.g.)
Pattern pat = Pattern.compile(",");
then whenever you wanted to use it, using:
pat.split(theString);
I have to convert binary data into text and I think I'm close, but something's not working quite right. In this case the output is supposed to be the letters "FRI", but I get a bunch of other symbols surrounding the letters:
F2eÊ)R¤I$I$I.
I don't know what seems to be the problem. This is the code:
public class DN06 {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
String location = "D:\\NetBeans\\Projects\\DN06\\src\\datoteka1.txt";
File newFile = new File(location);
Scanner sc = new Scanner(newFile);
StringBuilder sb = new StringBuilder();
String drek = "";
try{
while (sc.hasNext()){
String content = new String(sc.next().getBytes(),"UTF-8");
for (int i=0;i<=content.length()-8;i++){
int charCode = Integer.parseInt(content.substring(i,i+8),2);
drek += new Character((char)charCode).toString();
}
System.out.println(drek);
}
}catch( UnsupportedEncodingException e){
System.out.println("Unsupported character set");
}
}
}
In the line
String content = new String(sc.next().getBytes(),"UTF-8");
You already have your desired output. Here you already parsed the byte array you got to a String with the encoding UTF-8. After that you tried to decode it again into UTF-8 and hence you got a wrong result.
Edit:
Since the content of your File is written in binary, this will not be enough, you will have to parse every byte once. The problem in your for loop is, that you move the i always just one digit instead of 8 digits to the right in the binary string.
for (int i=0;i<=content.length()-8;i = i+8)
This should do the job, for real this time
I have a question about the snippet of code which I have underneath. I have a file called FILNAVN which is a file where the info the program needs is located. The first line of said file is a row of integers which I will only need read once. Will the code acutally do this? I ask because I haven't programmed the code inside the while-loop yet, and I could actually needs some tips as to how to do this as well :P
try{
Scanner leseFraFila= new Scanner(new File(FILNAVN)).useDelimiter(";");
int maaned=leseFraFila.nextInt();
int aar=leseFraFila.nextInt();
int totalFortjeneste=leseFraFila.nextInt();
int totaltAntallMaaneder=leseFraFila.nextInt();
int maanedsleieVanligHybel=leseFraFila.nextInt();
int maanedsleieToppHybel=leseFraFila.nextInt();
while(FILNAVN.hasNext()){
//Here is where I will probably use:
//String linje=leseFraFila.nextLine()
//linje.split(";");
//String .... =
//int ....=
}
}catch(IOException e){
System.out.print(e);
}
Here is a short, and simply solution to your problem:
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
All you have to do now is get the information to a string:
String readContent = readFile("test.txt", StandardCharsets.UTF_8);
OR you can use the defaultCharset().
All credit goes to erickson at his very informative post here
This is basically what I am trying to do.
I wanna take a File
Turn it into a Byte Array
Turn it into a String
Store it in a MySQL Table
Retrieve the String
Turn it back into a Byte Array
Turn it back into a File
Now, I have some code for you, which I tried to comment as best as I could. My problem is, that the file I get at the end of this code, doesn't come out right. It's missing information. It's a text file, so I should be able to tell whether the file is complete or not.
As far as I can see, it looks like I only get the last part of the file, and not the entire file. I am pretty sure I messing something up badly somewhere in this conversion. If you got suggestions on how to do this conversion and retrieval more efficiently (Still keeping the Database and all that in mind), please let me know as well!
The code is listed below
import java.io.*;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class main {
public static void main(String[] args) {
// The file we want to save.
File f = new File("build.xml");
try {
// Make it into a byte array first
FileInputStream fis = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for(int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
StringBuilder s = new StringBuilder();
// Now we simulate making it into a String, for easier storage
// in a database.
for(byte b : buf) {
// for debugging
s.append(b).append(",");
System.out.print(b +",");
}
// Now we want to retrieve the file from the database as a string
File someFile = new File("build2.xml");
FileOutputStream fos = new FileOutputStream(someFile);
// We count how many bytes there are in this string.
// One byte per Token.
StringTokenizer st = new StringTokenizer(s.toString(),",");
buf = new byte[st.countTokens()];
int i = 0;
StringBuilder t = new StringBuilder();
// Now we parse out all Bytes from the string, and put them into
// the prepared byte array.
while(st.hasMoreTokens()) {
byte b = Byte.parseByte(st.nextToken());
System.out.print(b + ",");
buf[i] = b;
i++;
// for debugging
t.append(b).append(",");
}
// Here I print true if both strings are exactly the same
// which they should be, which means that the bytes are intact
// before and after conversion.
System.out.println("\n" +(t.toString().equals(s.toString()) ? true : false));
// Here we would make the physical file on the machine.
fos.write(buf);
fos.flush();
fos.close();
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
http://pastebin.com/699yuE8f
Your approach is totally ignoring encodings, which is not a good thing. Characters are not equal to or equivalent to bytes.
If you have to do it in the sequence you describe, then create the string by something like this:
String intermediateString = new String(theByteArray,
theSameEncodingTheFileWasCreatedWith);
Likewise, when you convert the string back into bytes, get the bytes like this:
byte[] bytesToSave = intermediateString.getBytes(theSameEncodingTheFileWasCreatedWith);
But besides any of that, what's the point of using the string at all? Why not just store the bytes right into the database?
You simply messed up the string creation, and you don't read the bos but the buf.
for(byte b : >>buf<<) {
// for debugging
s.append(b).append(",");
System.out.print(b +",");
}
Otherwise I am not convinced that it will work or it is a good solution. Why can't you just store it simply in the database?
The code you shared is IMHO more complicated as it had to be.
Why do you read your text on byte-level if you are only interested in it's String representation?
I would prefer to read the file using an InputStreamReader. That allows you to directly operate on characters.
I got an unicode string from an external server like this:
005400610020007400650020007400ED0020007400FA0020003F0020003A0029
and I have to decode it using java. I know that the '\u' prefix make the magic (i.e. '\u0054' -> 'T'), but I don't know how transform it to use as a common string.
Thanks in advance.
Edit: Thanks to everybody. All the answers work, but I had to choose only one :(
Again, thanks.
It looks like a UTF-16 encoding. Here is a method to transform it:
public static String decode(String hexCodes, String encoding) throws UnsupportedEncodingException {
if (hexCodes.length() % 2 != 0)
throw new IllegalArgumentException("Illegal input length");
byte[] bytes = new byte[hexCodes.length() / 2];
for (int i = 0; i < bytes.length; i++)
bytes[i] = (byte) Integer.parseInt(hexCodes.substring(2 * i, 2 * i + 2), 16);
return new String(bytes, encoding);
}
public static void main(String[] args) throws UnsupportedEncodingException {
String hexCodes = "005400610020007400650020007400ED0020007400FA0020003F0020003A0029";
System.out.println(decode(hexCodes, "UTF-16"));
}
}
Your example returns "Ta te tí tú ? :)"
You can simply split the String in Strings of length 4 and then use Integer.parseInt(s, 16) to get the numeric value. Cast that to a char and build a String out of it. For the above example you will get:
Ta te tí tú ? :)
It can be interpreted as UTF-16 or as UCS2 (a sequence of codepoints coded in 2 bytes, hexadecimal representation), it's equivalent as long as we do not fall outside the BMP.
An alternative parsing method:
public static String mydecode(String hexCode) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<hexCode.length();i+=4)
sb.append((char)Integer.parseInt(hexCode.substring(i,i+4),16));
return sb.toString();
}
public static void main(String[] args) {
String hexCodes = "005400610020007400650020007400ED0020007400FA0020003F0020003A0029";
System.out.println(mydecode(hexCodes));
}