well, i am having problems with the code i made, i want to inject hexadecimal in a certain file, but when compiling comes an error message saying that some symbols are missing
String str = "rw";
String str2 = "test.so";
try {
raf = new RandomAccessFile(str2, str);
write(0x1234, "0100A0E3");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public void write(int i, String str) {
try {
raf.seek((long) i);
raf.write(Hex2b(str));
} catch (IOException e) {
e.printStackTrace();
}
could anyone tell which symbols are missing? I'm new to programming
Hex2b isn't a thing. I don't know where you got that from. Info on how to convert a string such as "0100A0E3" into bytes so that you can pass it as argument to raf.write can be found at this SO answer.
Related
In Java, I want to convert this:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
To this:
https://mywebsite/docs/english/site/mybook.do&request_type
This is what I have so far:
class StringUTF
{
public static void main(String[] args)
{
try{
String url =
"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
"%3Frequest_type%3D%26type%3Dprivate";
System.out.println(url+"Hello World!------->" +
new String(url.getBytes("UTF-8"),"ASCII"));
}
catch(Exception E){
}
}
}
But it doesn't work right. What are these %3A and %2F formats called and how do I convert them?
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The string you've got is in application/x-www-form-urlencoded encoding.
Use URLDecoder to convert it to Java String.
URLDecoder.decode( url, "UTF-8" );
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to
use URI, and to convert between these two classes using toURI() and
URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for
HTML form encoding, which is not the same as the encoding scheme
defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
I use apache commons
String decodedUrl = new URLCodec().decode(url);
The default charset is UTF-8
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
You can select your method wisely :)
If it is integer value, we have to catch NumberFormatException also.
try {
Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
I was having this problem too and came here as an answer. But I used the code of the friend whose question was approved, it didn't work. I tried something different and it worked, so I'm sharing the following line of code in case it helps.
URLDecoder.decode(URLDecoder.decode(url, StandardCharsets.UTF_8)))
I'm taking a course in Java, and the assignment is to write a calendar program that can write and retrieve events from a file.
My problem is that I'm only getting the first value of my written array. returned from the "input.readObject"
Here is my getFile method calling looking to read the file.
static String[] Entry = new String [35];
public static void getFile(Object month, String year) throws IOException
{
ObjectInputStream input = new ObjectInputStream(new FileInputStream(month+year+".txt"));
try
{
String[] LoadedEntry = (String[])(input.readObject());
Entry = (String[]) LoadedEntry;
}
catch (IOException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File not found, creating new file...");
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
input.close();
}
}
And the method that calls it, and writes the desired code after the getFile method executes.
public static void saveEvent(String month, int day, String year, String calendarEvent)
{
String[] EntryF = new String[35];
String[] Sample = {"1", "2", "3", "4", "5"};
try
{
getFile(month, year);
System.out.println("Past getFile");
EntryF = Entry;
//EntryF = Sample;
EntryF[day] = calendarEvent;
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(month + year+".txt", true));
output.writeObject(EntryF);
output.reset();
output.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Been racking my brain for all day, and cannot get this thing to work... Does anyone see where I went wrong?
I can verify that the object is being saved and passed down into the saveEvent method because the written textfile is changing, but it's just not reading in the full contents of the file correctly..
Thanks,
Andy
You will need a loop to read rest of the stream. So far you are reading just the first part of the stream, so the following will have to be in a loop:
String[] loadedEntry = (String[])(input.readObject());
And you will also need to determine a signal to use to end the loop.
For e.g. using input.read() will result in -1 when the end of stream is reached.
You can read the entire file with something like the following:
try {
while (Terminating_Condition) {
String[] loadedEntry = (String[]) (input.readObject());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope that helps.
In Java, I want to convert this:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
To this:
https://mywebsite/docs/english/site/mybook.do&request_type
This is what I have so far:
class StringUTF
{
public static void main(String[] args)
{
try{
String url =
"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
"%3Frequest_type%3D%26type%3Dprivate";
System.out.println(url+"Hello World!------->" +
new String(url.getBytes("UTF-8"),"ASCII"));
}
catch(Exception E){
}
}
}
But it doesn't work right. What are these %3A and %2F formats called and how do I convert them?
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The string you've got is in application/x-www-form-urlencoded encoding.
Use URLDecoder to convert it to Java String.
URLDecoder.decode( url, "UTF-8" );
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to
use URI, and to convert between these two classes using toURI() and
URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for
HTML form encoding, which is not the same as the encoding scheme
defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
I use apache commons
String decodedUrl = new URLCodec().decode(url);
The default charset is UTF-8
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
You can select your method wisely :)
If it is integer value, we have to catch NumberFormatException also.
try {
Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
I was having this problem too and came here as an answer. But I used the code of the friend whose question was approved, it didn't work. I tried something different and it worked, so I'm sharing the following line of code in case it helps.
URLDecoder.decode(URLDecoder.decode(url, StandardCharsets.UTF_8)))
I'm a beginner still, and currently learning about handling exceptions. The exercise in my book I'm trying to figure out tells me to add a Finally block to close out the file I opened, and I don't understand what I'm doing wrong. Keep in mind the file name and path are fake but here is what I have:
public static String readLineWithFinally()
{
System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = new RandomAccessFile("products.ran", "r");
try
{
String s = in.readLine();
return s;
}
catch (IOException e)
{
System.out.println(e.toString());
return null;
}
finally
{
try
{
in.close();
}
catch (Exception e)
{
System.out.println("Generic Error Message");
}
}
}
To add on to Taylor Hx's answer, you can take advantage of Java 7's try-with-resources construct to avoid having to use finally altogether in your case.
public static String readLineWithFinally() {
System.out.println("Starting readLineWithFinally method.");
try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
return in.readLine();
} catch (IOException e) {
System.out.println(e.toString());
return null;
}
}
You'll also want to be certain that your usage is consistent with what the API mandates for RandomAccessFile.
The code that you posted shouldn't compile, as RandomFile(String, String) can possibly throw FileNotFoundException. As such, we must include it in the try block.
System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
try {
in = new RandomAccessFile("products.ran", "r");
String s = in.readLine();
return s;
} catch (IOException e) {
System.out.println(e.toString());
return null;
} finally {
try {
if(in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("Generic Error Message");
}
}
Keep in mind the file name and path are fake but here is what I have:
That is why you will have a FileNotFoundException while creating RandomAccessFile("products.ran", "r") with read access mode "r".
From the documentation: RandomAccessFile(String name, String mode)
This constructor throws a FileNotFoundException if the mode is
"r" but the given string does not denote an existing regular file,
or if the mode begins with "rw" but the given string does not denote
an existing, writable regular file and a new regular file of that name
cannot be created, or if some other error occurs while opening or
creating the file
Listing my program fragment as below
public class InStream {
static FileOutputStream file=null;
static {
try {
file = new FileOutputStream("deo.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//when i try to replace below infinite loop,
//it is also not able to output my String
//while(ture)
or
//for(;;)
for(int i=0;i<100000;i++){
file.write("AB ".getBytes());
}
//file.flush();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run this program -> open deo.txt -> there are no data within this file
but when i comment the for loop just only test below fragment code:
try {
file.write("AB ".getBytes());
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Now i can see the "AB " string in the file. so strange....
Can any one do me a favor?
There is no error in your code. File "deo.txt" must be generate which contains AB AB...............
I tested your code. And it works. But for the deo.txt. You can check its size if it is about 293k. It displays nothing if you open it with Eclipse text editor. But you can view it with other system editor, such as notepad++.