Google API Translate not working for Language.HINDI - java

I am attaching the code below.
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class Translator {
public static void main(String[] args) {
// Translate trans = new Translate();
try{
System.setProperty("http.proxyHost", "192.16.3.254");
System.setProperty("http.proxyPort", "8080");
Translate.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
String translatedText = Translate.execute("How are you?", Language.ENGLISH, Language.HINDI);
System.out.println("translated text :" + translatedText);
}catch (Exception e) {
e.printStackTrace();
}
}
}
This is giving output as
translated text : ?? ???? ????
but for Language.FRENCH,Language.SPANISH its giving the translated text.
Could you please tell a solution for this.

If console can not display the chars correctly, it may caused by the Local Setting of the host operation system. If the system local is set to be English, then multi-bytes characters may not be displayed correctly. You can try to write it to a file and check it using a text editor, like Notepad++. And make sure you choose the correct encoding in Notepad++ :)

Related

Alt-codes only work in Java string when run within Netbeans

I have a small java program that reads a given file with data and converts it to a csv file.
I've been trying to use the arrow symbols: ↑, ↓, → and ← (Alt+24 to 27) but unless the program is run from within Netbeans (Using F6), they will always come out as '?' in the resulting csv file.
I have tried using the unicodes, eg "\u2190" but it makes no difference.
Anyone know why this is happening?
As requested, here is a sample code that gives the same issue. This wont work when run using the .jar file, just creating a csv file containing '?', however running from within Netbeans works.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Sample {
String fileOutName = "testresult.csv";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
Sample test = new Sample();
test.saveTheArrow();
}
public void saveTheArrow() {
try (PrintWriter outputStream = new PrintWriter(fileOutName)) {
outputStream.print("←");
outputStream.close();
}
catch (FileNotFoundException e) {
// Do nothing
}
}
}
new PrintWriter(fileOutName) uses the default charset of the JVM - you may have different defaults in Netbeans and in the console.
Google Sheet uses UTF_8 according to this thread so it would make sense to save your file using that character set:
Files.write(Paths.get("testresult.csv"), "←".getBytes(UTF_8));
Using the "<-" character in your editor is for sure not the desired byte 0x27.
Use
outputStream.print( new String( new byte[] { 0x27}, StandardCharsets.US_ASCII);

Java:Get Extension of file with "." in its name

Question might confuse you but read below for clarifications...
I am making a simple console project to get a extension of a file by inputting name from user.
I am using solution described here:
How do I get the file extension of a file in Java?
It solve my 90% problem
I have split file name on the basis of "." and "/".
But it will not run for input "a.out" or some otjer examples like this
it will give extension as ".out" actually being extension less
So is there any solution for thia case????
please help me
Sorry for my english
I assume you are looking for getting the extension of file without the .(Dot) and return empty string if there is no extension. The following code may provide the desired outcome.
public static void main(String[] args){
System.out.println(retrieveFileExtension("input.txt"));
}
private static String retrieveFileExtension(String fileName) {
try {
return fileName.substring(fileName.lastIndexOf(".") + 1);
} catch (Exception e) {
return "";
}
}

Java Spanish Encoding in Properties File

So I'm working on a localization example and the normal method of doing it with ResourceBundle and everything doesn't support UTF-8 it seems so I'm moving on to Properties.
I've got it getting the actual properties fine but in the Spanish file, it doesn't like the accents. I have it reading in UTF-8 but it doesn't care, just displays a different symbol than before.
Output:
íHola!
┐C¾mo estßs?
íAdi¾s!
Expected Output:
¡Hola!
¿Cómo estás?
¡Adios!
Properties File:
greetings = ¡Hola!
farewell = ¡Adiós!
inquiry = ¿Cómo estás?
Code:
import java.util.*;
import java.io.*;
public class Test{
public static void main(String[] args) throws IOException {
String language;
String country;
if (args.length != 2) {
language = new String("en");
country = new String("GB");
} else {
language = new String(args[0]);
country = new String(args[1]);
}
String file = String.format("lang_%s_%s.properties",language,country);
InputStream utf8in = Test.class.getClassLoader().getResourceAsStream(file);
Reader reader = new InputStreamReader(utf8in, "UTF-8");
Properties props = new Properties();
props.load(reader);
System.out.println(props.getProperty("greetings"));
System.out.println(props.getProperty("inquiry"));
System.out.println(props.getProperty("farewell"));
}
}
I've just spent about 40 minutes reading everything I could find and they were either the exact same as what I've got now or slightly different and when trying, produced the same results.
Can someone please tell me how I can get my expected output?
In Eclipse, I can be reproduced the problem. Here are steps:
Create Java project and set Text file encoding to CP850.
Create Run/Debug Configurations, set VM arguments to -Dfile.encoding=ISO8859-1.
Confirm Encoding setting in Common tab is CP850;
Run the java program.
When java program print to standard output, those chars become ISO8859-1 bytes.
Those bytes are re-encoded using CP850 and display in Console view.
This is a configuration problem. Make sure the Encoding is the same as the file.encoding of running program.

java codeformatter throwing NullPointerEception

I have one java code to format the another java code programaticlly.
The code is working fine for simple java code.But when i am introducing commnent in my input java code (input taken as String code) then in the following line textEdit is returned as null which is causing nullpointerexception in next steps.
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN , code, 0, code.length(), 0, null);
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
public class FormatCode {
public static void main(String[] args) {
String code = "public class TestFormatter{public static void main(String[] args){for(i=0;i<10;i++){i=i+2;\\abc"+"}System.out.println(\"Hello World\");}}";
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN , code, 0, code.length(), 0, null);
IDocument doc = new Document(code);
try {
textEdit.apply(doc);
System.out.println(doc.get());
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
Any hint to solve this issue.
Use commenting in new line.
The // comment is beeing used in one line so your code is like that.
In other words, to solve this issue, create /* comments instead.
This part {i=i+2;\\abc" should be {i=i+2;//abc\n" You need to use // for commenting not \ also you should create a newline after the comment otherwise the rest of your code will be on the same line and be commented out.
Basically, you got a null from codeFormatter.format, because, as the documentation says:
It returns null if the given string cannot be formatted.
As your program cannot be properly parsed (because of the comment issue), it can also not be formatted. You should check for a returned null from format() if there is any possibility that the texts it will be processing are not correct and formattable.

how to read from a txt file in blackberry eclipse?

i am developing an simple blackberry application in BlackBerry - Java Plug-in for Eclipse. In that, i want to read data from an external text file. I had searched for this, and tried for some tips, like. But failed at last. I will describe my application...
my main file...
package com.nuc;
import net.rim.device.api.ui.UiApplication;
public class Launcher extends UiApplication
{
public static void main(String[] args)
{
Launcher theApp = new Launcher();
theApp.enterEventDispatcher();
}
public Launcher()
{
pushScreen(new MyScreen());
}
}
And then my app class is like....
package com.nuc;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.GridFieldManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
public final class MyScreen extends MainScreen implements FieldChangeListener
{
// declared variables...
public MyScreen()
{
//rest codes...
I want to show some details from a text file before my app starts, like the End User License Agreement.. ie, something which cames as the first line..
my first question is, where i need to put that text file... i got lots of guidance from net, but nothing worked for eclipse..
Secondly, then how can i read the file and put its content in a dialog.
So plz guide me how i can achieve it.. sample code will be appreciable, for i am new to this environment...
To add a file to your Eclipe project
right click on the res folder of your project structure, click on New, click on Untitled Text File and then enter some text and save the file.
To read from a file and display on a dialog try something like the following code snippet:
try {
InputStream is = (InputStream) getClass().getResourceAsStream("/Text");
String str = "";
int ch;
while ((ch = is.read()) != -1) {
str += (char)ch;
}
synchronized (UiApplication.getEventLock()) {
Dialog.alert(str == null ? "Failed to read." : str);
}
} catch (Exception e) {
synchronized (UiApplication.getEventLock()) {
Dialog.alert(e.getMessage() + " + " + e.toString());
}
}
in the above code "/Text" is the file name. And if you got a NullPointerException then check the file name and path.
Rupak's answer is mostly correct, but there's a few problems with it. You definitely don't want to add immutable strings together in a situation like this. When you add 2 strings together (myString += "Another String") Java basically creates a new String object with the values of the two other Strings, because it cannot change the contents of the other strings. Usually this is fine if you just need to add two strings together, but in this case if you have a large file then you're creating a new String object for EVERY character in the file (each object bigger than the last). There's a lot of overhead associated with this object creation AND the garbage collector (very slow) will have to intervene more often because of all these objects that need to be destroyed.
StringBuffer to the rescue! Using a StringBuffer in place of the String concatenation will only require 1 object to be created and will be much faster.
try {
InputStream is = (InputStream) getClass().getResourceAsStream("/Text");
StringBuffer str = new StringBuffer();
int ch;
while ((ch = is.read()) != -1) {
str.append((char)ch);
}
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
Dialog.alert(str.toString() == null ? "Failed to read." : str.toString());
}
}
} catch (Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
Dialog.alert(e.getMessage() + " + " + e.toString());
}
}
}
Also several developers on the Blackberry support forums recommend against using UiApplication.getEventLock() because it can be "dangerous". They recommend using invokeLater() instead. See Blackberry Support Forums

Categories

Resources