This question already has answers here:
Why is Java BufferedReader() not reading Arabic and Chinese characters correctly?
(3 answers)
Closed 6 years ago.
i m trying to read a file having having arabic text and then i need to place read text in a text view..
following is the code i tried:
public static String readRawFile(Context ctx, int resId) throws UnsupportedEncodingException {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
text.append(line);
Log.e("Line Read", line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
but what i the file read is following
��(P3�EP ��qDDGP ��qD1QN-�EN#pFP ��qD1QN-PJEP ���
how should i read file such that the text read is in arabic
trying using only Bufferreader, with it i can read both arabic and english words at the same time. And you dont need the UT-8 encoding.
I hope this helps you:
public static void readArabic(String path) throws FileNotFoundException {
try(BufferedReader red = new BufferedReader(new FileReader(path));) {
String out;
while ((out = red.readLine()) != null){
System.out.println(out);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is the main method:
public static void main(String[] args) throws FileNotFoundException {
String path1 = "/Users/addodennis/Desktop/Projects/HotelReservation/src/Data/testAra";
readArabic(path1);
}
And this is the output:
I just copied some arabic text from the wikipedia page.
الأَبْجَدِيَّة العَرّة al-abjadīyah al-ʻarabīyah or الحُرُوف العَرَبِيَّة
’ī (هِجَائِي) or alifbā’ī (أَلِفْبَائِي)
يواجه مستخدمو الانترنت السوريون منذ بعض الوقت صعوبة في الدخول إلى موقع (ويكيبيديا
الولوج إلى صفحات موقع الموسوعة الحرة (ويكيبيديا)، وهو واحد من أشهر المواقع العالمية على الشبكة الدولية.
And if you still want to use StringBuilder then you can do this also:
public static String readArabic(String path) throws FileNotFoundException {
StringBuilder add = new StringBuilder();
try(BufferedReader red = new BufferedReader(new FileReader(path));) {
String out;
while ((out = red.readLine()) != null){
//System.out.println(out);
add.append(out);
}
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(add);
}
Related
I am trying to encode an XML to Base64 and then, write this Base64 to a JSON file.
When i do it, the Base64 is complete, but the JSON is incomplete, there is no trailing } at the end of string and it is incomplete, I do not know what could be do.
Here is my code:
This is the Xml to Base64 encoder
public static String fileEncoderBase64() throws IOException {
File file = new File("/root/EntradaN1.xml");
BufferedReader bufferedReader = null;
String linea;
String lineas = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
while ((linea = bufferedReader.readLine()) != null) {
lineas += linea;
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}
return encodeBase64(lineas);
}
public static String encodeBase64(String mensaje) throws UnsupportedEncodingException {
byte[] bytes = mensaje.getBytes("UTF-8");
return Base64.getEncoder().encodeToString(bytes);
}
And this is the JSON parser:
public static void jsonCreator(JsonModelAgent jsonModelAgent) throws IOException {
Gson gson = new Gson();
gson.toJson(jsonModelAgent, new BufferedWriter(new FileWriter("/root/datos.json")));
}
And this is de diferences between mongo's Base64 length and json's length.
JSON: ==============>65176
MONGO: =============>76592
Thanks for help.
just adding close to jsonCreator's fileWriter works
I am trying to do same in Eclipse to print a text file and highlight a particular line, but am only able to read text file and not the line in it. Following is my code:
import java.io.*;
public class Bible {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("temp.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Correct code to read a file line by line is
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Now comes the code to highlight.
There are multiple options to do it.
Use html codes in file e.g.
origString = origString.replaceAll(textToHighlight,"<font color='red'>"+textToHighlight+"</font>");
Textview.setText(Html.fromHtml(origString));
Use spannable texts
String text = "Test";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);
Use some third party library
EmphasisTextView and
Android TextView Link Builder
I wrtite parser without third-party libraries. Get html code from web site - http://www.cnn.com/ - but some part of code has unicode instead symbols, for example: "\u003cbr/>Sign in to your TV service provider to get access to \u003cbr/>" i think it is problem with encode - how i can fix it? Sorry for my English. Thank you.
public class Main {
public static void main(String[] args) throws IOException {
String commandLine = Scraper.readLineFromConsole();
Reader reader = Scraper.getReader(commandLine);
Scraper.writeInFileFromURL(reader);
}
public static class Scraper {
public static void writeInFileFromURL(Reader out) {
Reader reader = out;
BufferedReader br = new BufferedReader(reader);
try {
PrintWriter writer = new PrintWriter("newFile.txt");
String htmltext;
while (br.ready()) {
htmltext = br.readLine();
writer.write(new String(htmltext));
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readLineFromConsole() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String commandLine = null;
try {
commandLine = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return commandLine;
}
public static Reader getReader(String url)
throws IOException {
// Retrieve from Internet.
if (url.startsWith("http:") || url.startsWith("https:")) {
URLConnection conn = new URL(url).openConnection();
return new InputStreamReader(conn.getInputStream());
}
// Retrieve from file.
else {
return new FileReader(url);
}
}
}
}
Consider following
Code
private String url = "https://celestrak.org/NORAD/elements/resource.txt";
#Override
public Boolean crawl() {
try {
// Timeout is set to 20s
Connection connection = Jsoup.connect(url).userAgent(USER_AGENT).timeout(20 * 1000);
Document htmlDocument = connection.get();
// 200 is the HTTP OK status code
if (connection.response().statusCode() == 200) {
System.out.println("\n**Visiting** Received web page at " + url);
} else {
System.out.println("\n**Failure** Web page not recieved at " + url);
return Boolean.FALSE;
}
if (!connection.response().contentType().contains("text/plain")) {
System.out.println("**Failure** Retrieved something other than plain text");
return Boolean.FALSE;
}
System.out.println(htmlDocument.text()); // Here it print whole text file in one line
} catch (IOException ioe) {
// We were not successful in our HTTP request
System.err.println(ioe);
return Boolean.FALSE;
}
return Boolean.TRUE;
}
Output
SCD 1 1 22490U 93009B 16329.83043855 .00000228 00000-0 12801-4 0 9993 2 22490 24.9691 122.2579 0043025 337.9285 169.5838 14.44465946256021 TECHSAT 1B (GO-32) 1 25397U ....
I am trying to read an online-txt file (from https://celestrak.org/NORAD/elements/resource.txt). Problem is that while I print or save the body's text it prints whole online-txt file in one line. But I want to read it as splited by \n so that I can read it line by line. Am I making mistake while reading online-txt file?
I am using JSoup.
you can do it without using jsoup in the following manner:
public static void main(String[] args) {
String data;
try {
data = IOUtils.toString(new URL("https://celestrak.com/NORAD/elements/resource.txt"));
for (String line : data.split("\n")) {
System.out.println(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
the above code uses org.apache.commons.io.IOUtils
if adding the commons library is a issue you can use the below code:
public static void main(String[] args) {
URLReader reader;
try {
reader = new URLReader(new URL("https://celestrak.com/NORAD/elements/resource.txt"));
BufferedReader bufferedReader = new BufferedReader(reader);
String sCurrentLine;
while ((sCurrentLine = bufferedReader.readLine()) != null) {
System.out.println(sCurrentLine);
}
bufferedReader.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Since the file is already delimited by line separator, we can simple take the input stream from URL to read the contents
String url = "https://celestrak.com/NORAD/elements/resource.txt";
List<String> text = new BufferedReader(new InputStreamReader(new URL(url).openStream())).lines().collect(Collectors.toList());
To convert to a String
String content = new BufferedReader(new InputStreamReader(new URL(url).openStream())).lines()
.collect(Collectors.joining(System.getProperty("line.separator")));
I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}