Java reads ANSI file incorrectly - java

I tried to read an ANSI encoded Arabic file in Java using the following two way
Scanner scanner = null;
try {
scanner = new Scanner(new File("test/input.txt"), "ISO-8859-6");
while (scanner.hasNextLine()) {
String input =scanner.nextLine();
processString(input);
}
I tried also to read with default encoding (i.e. I omitted the "ISO-8859-6")
Any suggestions?

Try this code:
public static void transform(File source, String srcEncoding, File target, String tgtEncoding) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(source), Charset.forName(srcEncoding)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding));
char[] buffer = new char[16384];
int read;
while ((read = br.read(buffer)) != -1) {
bw.write(buffer, 0, read);
}
} finally {
try {
if (br != null) {
br.close();
}
} finally {
if (bw != null) {
bw.close();
}`enter code here`
}
}
}

Look at this:
private static final String FILENAME = "/Users/jucepho/Desktop/ansi.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
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();
}
}
}
This file has this characters http://www.alanwood.net/demos/ansi.html

Related

Java PrintWriter printing multiple blank lines at the beginning of each file

I have used PrintWriter for long time and I have never encounted with this problem. See below
When I open the csv file using excel the first element of the headerline disapeared.
To further investigate, I found a couple of blank lines inserted at the beginning when opening it using text file.
below is my code:
print header line:
public void printHubInboundHeader() {
try {
StringBuilder sb = new StringBuilder();
String headingPart1 = "Inbound_Hub, Date, Time,";
String headingPart2 = "Weight";
sb.append(headingPart1+headingPart2);
System.out.println(sb);
FileWriter.writeFile(sb.toString(),"filepath");
}
catch(Exception e) {
System.out.println("Something wrong when writting headerline");
e.printStackTrace();
}
}
print actual data:
public void printHubSummary(Hub hub, String filePath) {
try {
StringBuilder sb = new StringBuilder();
String h = hub.getHub_code();
String date = Integer.toString(hub.getGs().getDate());
String time = hub.getGs().getHHMMFromMinute(hub.getGs().getClock());
String wgt = Double.toString(hub.getIb_wgt());
sb.append(h+","+date+","+time+","+wgt);
// System.out.println("truck print line: " + sb);
FileWriter.writeFile(sb.toString(),filePath);
}
catch (Exception e) {
System.out.println("Something wrong when outputing truck summary file!");
e.printStackTrace();
}
}
the file writer code:
public class FileWriter {
private static String filenameTemp;
public static boolean creatFile(String name) throws IOException {
boolean flag = false;
filenameTemp = name + "";
System.out.println("write to file: "+filenameTemp);
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
else {
filename.delete();
filename.createNewFile();
flag = true;
}
return flag;
}
public static boolean writeFile(String newStr, String filename) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filename);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
public static void setFileName(String fileName){
filenameTemp = fileName;
}
}
I don't know if this is the only problem with your code, but every call to your FileWriter.writeFile adds a new Byte Order Marker to the file. This means you end up with several markers in the file, and this may confuse some tools.
To remove the extra BOM in FileWriter.writeFile, you can use the deleteCharAt method:
...
buf = buf.append(System.getProperty("line.separator"));
}
if (buf.length() > 0 && buf.charAt(0) == '\uFEFF') {
buf.deleteCharAt(0);
}
buf.append(filein);

Writing socket stream to file takes long

I have code which writes the inputstream from a socket to a file with a bufferedreader. This works, but for some reason it takes a long time for the bufferedwriter to finish writing to the file (multiple minutes, of which less than first 2 seconds are spent writing to the file). The code is as follows:
#Override
public void handleRequest() {
Socket s = null;
BufferedReader br = null;
Writer writer = null;
PrintWriter pw = null;
try {
s = new Socket(this.getHost(), this.getPort());
pw = new PrintWriter(s.getOutputStream());
pw.println(this.getHTTPCommand());
pw.println(this.getHostCommand());
pw.print(ENDOFREQUEST);
pw.flush();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String currentDir = System.getProperty("user.dir");
String filePath = this.getPath();
if(this.getPath().equals("/")){
filePath = "/index.html";
}
Path completePath = Paths.get(currentDir, filePath);
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(completePath.toString()), "utf-8"));
String t;
while((t = br.readLine()) != null){
writer.write(t + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (writer != null) {
writer.close();
}
if (br != null) {
br.close();
}
if (pw != null) {
pw.close();
}
if (s != null) {
s.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
You probably need to flush the BufferedWriter after your while loop. It doesn't affect how your code works, but a try-with-resources would tidy up the code as well.

I am making the bible app and I want to print a particular chapter and highlight a particular line

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

Java, copy from a file to another, line by line with an interval

I have a file with 120 lines and I want to move them one by one to another file with an interval for example of 1 seconds and to be able to find after 10 seconds 10 lines in the new file.
But for my case, I execute the program with 0 lines in the new files until the end, and then I find the data.
String sourceFileName = "D:\\oldfile.txt";
String destinationFileName = "D:\\newfile.txt";
if(evt.getSource() == btnProcess)
{
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader(sourceFileName));
pw = new PrintWriter(new FileWriter(destinationFileName));
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
Thread.sleep(1000);
}
br.close();
pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
Second, for 4 files to process in the same moment with different interval, I need to use Threads ?
Thanks for your help.
When you are writing to a text file, PrintWriter does not write it to disk immediately. Instead, it keeps the data in a buffer in memory.
You could manually flush the buffer to when you need data to be on disk. Just after println() call flush() as below.
while ((line = br.readLine()) != null) {
pw.println(line);
pw.flush();
Thread.sleep(1000);
}
You can call a
pw.flush();
directly after
pw.println(line);
This should do the trick.
As for your second part, you could do something like this, if you do not want to use threads:
public static void main(final String[] args) {
FileCopyDto[] files = new FileCopyDto[] {
new FileCopyDto("D:\\oldfile.txt", "D:\\newfile.txt", 5),
new FileCopyDto("D:\\oldfile2.txt", "D:\\newfile2.txt", 1)
};
try {
boolean dataAvailable = true;
int secondCount = 0;
while (dataAvailable) {
dataAvailable = false;
for (FileCopyDto d : files) {
d.write(secondCount);
dataAvailable = dataAvailable || d.isDataAvailable();
}
secondCount++;
Thread.sleep(1000);
}
for (FileCopyDto d : files) {
d.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
static class FileCopyDto {
String sourceFileName;
String destinationFileName;
int timeInSeconds;
BufferedReader br = null;
PrintWriter pw = null;
String nextLine;
public FileCopyDto(final String sourceFileName,
final String destinationFileName,
final int timeInSeconds) {
this.sourceFileName = sourceFileName;
this.destinationFileName = destinationFileName;
this.timeInSeconds = timeInSeconds;
}
public void open() throws IOException {
br = new BufferedReader(new FileReader(sourceFileName));
pw = new PrintWriter(new FileWriter(destinationFileName));
}
public boolean isDataAvailable() throws IOException {
if (br == null) {
open();
}
return (nextLine == null) || ((nextLine = br.readLine()) != null);
}
public void write(final int secondCount) {
if (nextLine != null && secondCount % timeInSeconds == 0) {
pw.println(nextLine);
pw.flush();
nextLine = null;
}
}
public void close() throws IOException {
br.close();
pw.close();
br = null;
}
}

how can i put a filter on a CSV File stored in an Arraylist...Using Java

Iam reading a Csv file and want to put a filter on that arraylist in which the whole Csvfile is stored...
I'm new to Java Can anyone Correct me where m going wrong...
public static void main(String[] args) throws IOException {
String csvFile = "File.csv";
BufferedReader br = null;
String line ="";
ArrayList<CSVRead> alist=new ArrayList<CSVRead>();
try {
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null)
{
String StoringArray[] = line.split(",");
CSVRead Cs1 = new CSVRead((StoringArray[0]),(StoringArray[1]),(StoringArray[2]),(StoringArray[3]),(StoringArray[4]),(StoringArray[5]), (StoringArray[6]), (StoringArray[7]),(StoringArray[8]),(StoringArray[9]),(StoringArray[10]),(StoringArray[11]),(StoringArray[12]),(StoringArray[13]), (StoringArray[14]),(StoringArray[15]),(StoringArray[16]),(StoringArray[17]));
alist.add(Cs1);
}
alist.forEach(Cs1 -> System.out.println("\t" + Cs1));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
Try it
public static void main(String[] args) throws IOException {
String csvFile = "File.csv";
BufferedReader br = null;
String line ="";
ArrayList<String> alist=new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null)
{
String StoringArray[] = line.split(",");
for (String i : StoringArray){
alist.add(i);
}
}
System.out.println(alist); // print all list values
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}

Categories