I have an XML file for which I want to determine the encoding programmatically. The XML file is present on the device and the dataFilePath contains the path. The encoding declaration in the file says it is UTF-8 but when I check the encoding in Notepad ++ the file is ANSI encoded.
Here's what I have tried
String encoding;
FileReader reader1 = null;
XMLStreamReader xmlStreamReader = null;
reader1 = new FileReader(dataFilePath);
xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(reader1);
encoding = xmlStreamReader.getEncoding();
InputStream inputStream = new FileInputStream(dataFilePath);
Reader reader =
new InputStreamReader(inputStream, Charset.forName(encoding));
encoding always returns null and an exception is raised
Related
I'm trying to adjust the accent in my code but it's not working, like below:
byte[] nBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(TagsConvert(texto));
socket.Send(nBytes);
The result is like this in the printer: tri?ngulo, I need the result to be triângulo.
Another previous attempt I made was:
byte[] reset = Encoding.ASCII.GetBytes("\x0A");
byte[] nBytes = Encoding.ASCII.GetBytes(TagsConvert(texto));
socket.Send(nBytes);
socket.Send(reset);
I wasn't successful either.
I would like to parse an UTF8 format XML with libXML2.
My code is write in C and I use v2.9.3 of libXML2.
My code follow:
xmlTextReaderPtr reader;
xmlTextWriterPtr writer;
writer = xmlNewTextWriterFilename("test.xml", 0);
xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL);
xmlTextWriterStartElement(writer, BAD_CAST "node_with_é_character");
xmlTextWriterEndElement(writer);
xmlTextWriterEndDocument(writer);
xmlFreeTextWriter(writer);
reader = xmlReaderForFile("test.xml", "UTF-8", XML_PARSE_RECOVER);
int ret = 1;
while (ret == 1) {
const xmlChar *nameT = xmlTextReaderConstName(reader);
printf("\n ---> %s\n",nameT);
ret = xmlTextReaderRead(reader);
}
Output is :
---> (null)
---> node_with_é_character
Problem is "node_with_é_character" trace and not "node_with_é_character"
My command prompt is "chcp 1252" set.
I don't understand why liXML2 cannot store/read the "é" character.
As noted in comment your under Windows, so I guess it's likely your source code is not UTF-8 encoded, so the C string "node_with_é_character" is not UTF-8 encoded in your executable.
I don't know libxml2 interfaces, but code example is quite clear it expects input parameters in UTF-8. See http://xmlsoft.org/examples/testWriter.c
/* Write a comment as child of EXAMPLE.
* Please observe, that the input to the xmlTextWriter functions
* HAS to be in UTF-8, even if the output XML is encoded
* in iso-8859-1 */
tmp = ConvertInput("This is a comment with special chars: <\xE4\xF6\xFC>",
MY_ENCODING);
Save your source file as UTF-8 will help you fix your issue.
I need to Convert a xamarin forms image into a base64 format, Can anyone help me with this?
This is how i've being trying to do it, but it doesent work.
var inputStream = signatureImage.Source.GetValue(UriImageSource.UriProperty);
//Getting Stream as a Memorystream
var signatureMemoryStream = inputStream as MemoryStream;
if (signatureMemoryStream == null)
{
signatureMemoryStream = new MemoryStream();
inputStream.CopyTo(signatureMemoryStream);
}
//Adding memorystream into a byte array
var byteArray = signatureMemoryStream.ToArray();
//Converting byte array into Base64 string
base64String = Convert.ToBase64String(byteArray);
"signatureImage" is the image name.
Once you get your file path , you can use the following code that worked for me.
var stream = file.GetStream();
var bytes = new byte [stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = System.Convert.ToBase64String(bytes);
I found it here
Image is just a control in Xamarin forms to display the image.
It is not something from which you can get your image byte array out.
You will be better of using the Media Plugin and save it to disk. Then load it via memory stream and convert.
You can also use FFImageLoading. It has 2 methods which can be of use for you :
GetImageAsJpgAsync(int quality = 90, int desiredWidth = 0, int desiredHeight = 0)
GetImageAsPngAsync(int desiredWidth = 0, int desiredHeight = 0)
The SO question - Convert Image into byte array in Xamarin.Forms shows how to do it in Platform specific code here.
The forum thread (Convert Image to byte[]) has a good discussion on why you can't get it from the control.
You can do this as below as well
var base64String = Convert.ToBase64String(File.ReadAllBytes(file.Path))
I tried to get the image from clipboard when I press ctrl+v on a page, with the code from a gist, which will console.log the image content it gets.
I found the image content is a long base64 string with a special prefix:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAUCAYAAADStFABAAAJHElEQVRYCXVXWXObVxl+Pu2yFsuyLMnxHtdpY8c4pHXpt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u/ilTTAZKW/bE1RiJO9I7geeHT+FtuRCw/Oh2h9AlFyDJVXdKLDVUmhWc7suRTbzdweEiEYc7nz1xHfxhI2kSnCffmUV1bAypU9lOfXE0enrRlsusKa0hK1+M9yFVO0V1dBT9s+8aW9qT6IgYdMJGSp5/RwowjKWNLEpyF9RkB7XkTWeriQ55Sy+yKDuH0D8+a2z4wwIQTwuhSVwcm0HESmI7nWX95I6RI9CWYyqNY/IoiyCJi2OXO/EQk4utuTI+a35+vs3KqhOOKeCZPtnaQvbhA3ikEOfemEAsmZSo5I3ezeKr9eeoyb2RvHoNgUHZmmKjBaUD4hBDC0zHxfwmcmt/hd+dRf9QAjH52iTt7+2ZD5xqox/xie/KzhsxiROTOFpQYiiRv1fYwbONR6ghj9GBEcS/xssJ3sZ2Bt52N2bGryIR+W98xCQRU3O1UqlUWxNQh6w2HXrl5ke5jPzKCg7X1+WOyBqAUCKJqNwZPZOT5sKsyCtBYiHZiGNfPXXokye2WSsi/9UiDrMrKBd3jF0gPIiexCSiAzNwyD3BS8serNpTmXz6IBGv1qpifWcZ2/vrck3JHSZfc9FIAkPxNzDWPymXpV9ejXoHj7aKzUUyeHNzc20NXFdQnZJPxUAgYBzqSlDvVHZHqVRCVb4Z7CtOGxaAPOqRFJ9j8kOhEDwejzmX9MUgmfjJyYnBUxv604DJ0wIQQ4k6QXkluGAaH/HouyAfdfqtQVsuDmNRHO3Nv9K6LdQRewZHJYIQlA50p5Cvcl4wTFoLRxmDVAfkK3FMPAZHIh5xGbBiaME4Vz/kaSMG9dmTxzHjI5b6JTZt6cvOo402xTZ2ymSvRAGVlBiQBkWeBsTx63rkKRb1mCTn1GMjj8GpHuck9pRrUZRPv4yHRLnGpjyNi3MtDnXteelYMSknkU+b/wD4ldY7nz0NzAAAAABJRU5ErkJggg==
How to decode it to binary? I tried to remove the prefix data:image/png;base64, and use a base64 library to decode the rest into binary, and save it to a image.png file. But the file can't be displayed, with invalid format error.
But if I paste the whole string to http://base64online.org/decode/, it can play the image as well.
The base64 library I used is https://github.com/wstrange/base64, and my code is:
import 'package:base64_codec/base64_codec.dart';
var body = /* the long str above */;
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bs = Base64Codec.codec.decodeList(bStr.codeUnits);
var file = new File("image.png");
file.writeAsBytesSync(bs);
I don't know where is wrong :(
Try using the crypto package from the Dart SDK. This creates an image.png that opens fine (I believe it's this image... )
library foo;
import 'package:crypto/crypto.dart';
import 'dart:io';
void main() {
var body = "data:image/png;base64,iVBORw0KGgoAAAANSUh... snip";
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bytes = CryptoUtils.base64StringToBytes(bStr); // using CryptoUtils from Dart SDK
var file = new File("image.png");
file.writeAsBytesSync(bytes);
}
You'll need to add crypto to your pubspec.yaml :
dependencies:
crypto: any
The library linked at https://github.com/wstrange/base64, also notes in the README:
Deprecated
Note: The Dart SDK now includes a Base64 codec with url safe options. Unless you need streaming support, you should use the SDK methods as they are slightly faster.
See CryptoUtils
See also How to native convert string -> base64 and base64 -> string
Decoding as a string and then writing the bytes works:
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bs = Base64Codec.codec.decodeString(bStr);
var file = new File("image.png");
file.writeAsBytesSync(bs.codeUnits);
The easiest approach is:
import 'dart:convert';
final result = base64Decode(stringValue);
I am reading a name of the file/script from an utf-8 encoded XML file. This is then passed to VBScript. VBScript starts a second program to which this passed program/script is provided as an argument. When the argument is in English, the VBScript executes successfully.
But if the name read from XML is non-english( Russian in my case ), VBScript fails to find that file.
I am running VBScript from Java code only using "cscript" as I am running it on Windows.
However, if I copy the command fired by Java program to run VBScript, and paste it on command prompt, it executes normally despite the argument name is in non-english language.
I then hardcoded file/script name in VBScript. Changed encoding of VBScript to UCS2-LE, and directly run it from command prompt. It executed normally. It failed to execute for any other encoding used for VBScript. Also the non-english text is displayed as ? in any other encoding than UCS2-LE.
Then I tried to encode file/script name into UTF16-LE in Java and then passed it to VBScript. Irrespective of which encoding was used in VBScript, it fails. Again if I copy the command printed on standard output from Java program and run it from cmd, it executes.
The command printed from Java displays non-english text correctly.
Can anyone please help me to resolve the issue?
Any relative help would be greatly appreciated.
This is what I am doing currently. I need to pass an argument contatining Russian Text to VBScript from Java.
I tried to use two different approaches.
First approach in the code below writes the Russian text in a file using encoding UnicodeLittle. File is found to be in encoding UCS-2LE. And then VBScript reads the value from that file, and script is executed successfully.
In second approach, I tried to directly pass encoded Russian text as argument to script. VbScript fails saying that script can't be opened.This is the approach I want solution for.
Below is the Java code attached.
Any help would be greatly appreciated.
public class CallProgram
{
private static String encodeType = "UnicodeLittle";
private File scriptName = new File( "F:\\Trial Files\\scriptName.txt" );
public static void main(String[] args)
{
CallProgram obj = new CallProgram();
Runtime rt = Runtime.getRuntime();
try
{
**//Approach1 - Writes text to file and calls vbscript which reads text from file and uses it as an argument to a program**
String sName = "D:\\CheckPoints_SCRIPTS\\Менеджер по качеству"; //Russian Text
byte [] encodedByte= sName.getBytes( encodeType );
String testCase = new String( encodedByte, encodeType ); //New string containing russian text in UnicodeLittle encoding...
obj.writeToFile( testCase ); //Writing russian string to file...
String mainStr = "cscript /nologo \"D:\\Program Files\\2.0.1.3\\Adapter\\bin\\scriptRunner_FileRead_Write.vbs\"";
Process proc1 = rt.exec( mainStr );
int exit = proc1.waitFor();
System.out.println( "Exit Value = " + exit );
**//Approach 2 - Passing encoded Russian text directly to VbScript...**
//This is not working for me...
String [] arrArgs = { "cscript", "/nologo", "\"D:\\Program Files\\IBM\\Rational Adapters\\2.0.1.3\\QTPAdapter\\bin\\scriptRunner.vbs\"", testcase };
ProcessBuilder process = new ProcessBuilder( arrArgs );
Process proc2 = process.start();
proc2.waitFor();
}
catch (IOException e)
{
e.printStackTrace();
}
catch ( InterruptedException intue )
{
intue.printStackTrace();
}
}
//Function to write Russian text to file using encoding UnicodeLittle...
private void writeToFile( String testCase )
{
FileOutputStream fos = null;
Writer out = null;
try
{
fos = new FileOutputStream( this.scriptName );
out = new OutputStreamWriter( fos, encodeType );
out.write( testCase );
out.close();
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch ( IOException ioe )
{
ioe.printStackTrace();
}
finally
{
try
{
if ( fos != null )
{
fos.close();
fos = null;
}
if ( out != null)
{
out.close();
out = null;
}
}
catch( IOException ioe )
{
fos = null;
out = null;
}
}
} // End of method writeToFile....
}
I've resolved similar problems before by using the short 8.3-style filename instead of the long filename. I get this short name using the ShortPath method of FileSystemObject. Here's a VBScript example... you may want to try something similar in Java.
Function GetShortPath(strLongPath)
Dim FSO
Dim objFolder
Dim objFile
Dim strShortPath
Set FSO = CreateObject("Scripting.FileSystemObject")
' Is it a file or a folder?
If FSO.FolderExists(strLongPath) Then
' It's a folder.
Set objFolder = FSO.GetFolder(strLongPath)
strShortPath = objFolder.ShortPath
ElseIf FSO.FileExists(strLongPath) Then
' It's a file.
Set objFile = FSO.GetFile(strLongPath)
strShortPath = objFile.ShortPath
Else
' File not found.
strShortPath = ""
End If
GetShortPath = strShortPath
End Function
For example,
Debug.Print GetShortPath("C:\öêåéèüø.çõâ")
returns C:\B373~1, which can be used in place of the long filename with non-English characters. Example with dir /x (reveals the short filename) and notepad:
C:\sandbox>dir /x
Volume in drive C has no label.
Volume Serial Number is BC90-DF37
Directory of C:\sandbox
13/01/2011 15:12 <DIR> .
13/01/2011 15:12 <DIR> ..
13/01/2011 14:52 22 NEWTEX~1.TXT New Text Document.txt
13/01/2011 15:05 0 C7F0~1.TXT öêåéèüø.txt
13/01/2011 15:05 0 B373~1 öêåéèüø.çõâ
3 File(s) 22 bytes
2 Dir(s) 342,158,913,536 bytes free
C:\sandbox>notepad B373~1