I wrote a Java program to take the lines of a file, and sort out a specific id which will then be converted to ASCII characters from HEX. Worked great for a couple of files until it found out the "0D" HEX character which seems to be carriage return (no idea what that does).
When it encounters that, it ends the line output (which it shouldn't do). I can't figure out what's happening.
This is the code, which compiles with no error. I've attached a picture with the result.
The file 1 contains the characters until the ID=xxx:LENGHT=8 and after that the 8 HEX characters needed to convert. after that, the program converts and add the text in the same line. I need them to be on the same line to figure out the pattern.
import java.io.*;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
public class FrameDecoder {
public static void main(String[] args) throws IOException {
try {
// Sortam frameurile cu id-ul tinta
File fisierSursa = new File("file1.txt"); //Fisierul original
FileWriter fisierData = new FileWriter("file2.txt"); //Fisierul cu frameurile care au id-ul cautat
FileWriter fisierTranzit = new FileWriter("file3.txt"); //Fisier cu caractere HEX, care va fi sters.
Scanner citireSursa = new Scanner(fisierSursa);
while (citireSursa.hasNextLine()){
String data = citireSursa.nextLine();
//System.out.println("data = " + data);
int intIndex = data.indexOf("ID=289"); // idul pe care il cauti
int intIndex2 = data.indexOf("ID=1313"); //al doilea id pe care il cauti
if (intIndex != -1 || intIndex2 != -1){
char[] text = data.toCharArray();
int counter = 0;
for (int i=0; i<text.length; i++){
if (text[i] == ':' && counter < 5){
counter++;
}
if (text[i] == ':' && counter == 5){
fisierTranzit.write(text[i+1]);
fisierTranzit.write(text[i+2]);
}
}
fisierTranzit.write("\r\n");
fisierData.write(data + "\r\n");
}
}
citireSursa.close();
fisierTranzit.close();
fisierData.close();
// Convertire HEX to ASCII
FileWriter fisierAscii = new FileWriter("file4.txt"); //Fisier care va contine caraterele ASCII decodate
File fisierTranzitRedeschis = new File("file3.txt"); //Reinitializam fisierul tranzit pentru a putea citi din el
Scanner citireTranzit = new Scanner(fisierTranzitRedeschis);
while (citireTranzit.hasNextLine()){
String data2 = citireTranzit.nextLine();
System.out.println("data2 = " + data2);
if (data2.length() % 2 != 0){
System.err.println("Invalid hex string!");
return;
}
StringBuilder builder = new StringBuilder();
for (int i=0; i<data2.length(); i=i+2){
//Impartim sirul in grupe de cate doua caractere
String s = data2.substring(i, i+2);
//Convertim fiecare grup in integer folosinf valueOfTheMetod
int n = Integer.valueOf(s, 16);
//Convertim valoare integer in char
builder.append((char)n);
}
fisierAscii.write(builder.toString() + "\r\n");
//System.out.println(builder.toString());
}
citireTranzit.close();
fisierAscii.close();
//Stergem fisierul 3
File stergereFisier3 = new File("file3.txt");
if(stergereFisier3.delete()){
System.out.println("File 3 deleted successfully");
}else{
System.out.println("Failed to delete file 3");
}
// Combinam fisierele
PrintWriter fisierFinal = new PrintWriter("file5.txt");
BufferedReader br1 = new BufferedReader(new FileReader("file2.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("file4.txt"));
String line1 = br1.readLine();
String line2 = br2.readLine();
//loop to copy lines
//of file1.txt and file2.txt
//to file3.txt alternatively
while (line1 != null || line2 !=null){
if(line1 != null){
fisierFinal.print(line1 + " ");
line1 = br1.readLine();
}
if (line2 != null){
fisierFinal.println(line2 );
line2 = br2.readLine();
}
}
fisierFinal.flush();
//closing resources
br1.close();
br2.close();
fisierFinal.close();
System.out.println("Merged files succesfully");
//Stergem fisierul 2 si 4
File stergereFisier2 = new File("file2.txt");
File stergereFisier4 = new File("file4.txt");
if(stergereFisier2.delete() && stergereFisier4.delete()){
System.out.println("Files 2 and 4 deleted successfully");
}else{
System.out.println("Failed to delete files 2 and 4");
}
}catch (FileNotFoundException e){
System.out.println("An error occurred.");
e.printStackTrace();
}catch (IOException e){
System.out.println("No data to print");
e.printStackTrace();
}
}
}
Edit: I've cheated a little and place a condition when printing the HEX characters, if encounters 0D, just replacem them with 00. It worked. I'll also try your method, that one seems more ok than mine.
for (int i=0; i<text.length; i++){
if (text[i] == ':' && counter < 5){
counter++;
}
if (text[i] == ':' && counter == 5){
if(text[i+1] == '0' && text[i+2] == 'D'){
fisierTranzit.write('0');
fisierTranzit.write('0');
}
else{
fisierTranzit.write(text[i+1]);
fisierTranzit.write(text[i+2]);
}
}
}
The carriage return character \r (hex 0D) is one of the standard line separator characters, and Scanner.hasNextLine() and nextLine() methods assume it must terminate the current line.
To get more control, set the delimiter for Scanner to just the line feed character \n and use hasNext/next methods instead of hasNextLine/nextLine methods. For example:
Scanner citireTranzit = new Scanner(fisierTranzitRedeschis);
citireTranzit.useDelimiter("\n");
while (citireTranzit.hasNext()){
String data2 = citireTranzit.next();
...
}
I have a problem with my java program. I have to read lines from a file, the form of these lines is:
1#the^cat#the^dog#the^bird#^fish#bear
2#the^cat#the^dog#the^bird#^fish#bear
and print all, accept the "#" and "^" at textfields in my GUI. The "^" must appear in case there in not article. For exaple ^fish, i have to print it as ^fish but the^dog i have to print the dog.
As far i can read and print the lines in the textfields but i can't find a way to skip the "^" between the words.
Here is my code:
try {
FileReader file = new FileReader("C:\\Guide.txt");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i=0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line "+i+" <"+line+">");
String[] words = line.split("#");
if (words.length != 7) continue;
number=words[0];
onomastiki=words[1];
geniki=words[2];
aitiatiki=words[3];
klitiki=words[4];
genos=words[5];
Region=words[6];
E = new CityEntry(number,onomastiki,geniki,
aitiatiki,klitiki,
genos,Region);
Cities.add(E);
}
You can try something like this.
FileReader file = new FileReader("C:\\\\Users\\\\aq104e\\\\Desktop\\\\text");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i = 0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line " + i + " <" + line + ">");
String[] words = line.split("#");
for (int j = 0; j < words.length; j++) {
if(words[j].contains("^")) {
if(words[j].indexOf("^") == 0) {
// write your code here
//This is case for ^fish
}else {
// split using ^ and do further manipulations
}
}
}
}
}
Let me know if this works for you.
That is gonna work, but it is not best way)
foreach(String word : words){
if(word.contains"the"){
word.replace("^"," ");
}
}
I'm trying to do a simple login from a textfile. I've used different ways of reading the text from the file to a String line(BufferedReader and Scanner). I am able to get the line into a string, but it doesn't want to compare the 2 strings and match when I use an if statement(.equals()) or even if I use .equalsIgnoreCase(). When I print the 2 strings to be compared they are the same. but my if statement doesn't seem to return true?
This was the last coding i tried (I thought maybe if I put it into an array it would compare true, but still nothing).
Iv'e looked and saw similar questions to comparing strings from textfile, but never saw a problem with the if statement to return true
import java.io.*;
import java.text.*;
import java.lang.*;
public class tes
{
public static void main(String[] args)throws Exception
{
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
}
}
I've tried to execute your code and everything worked as expected. I received "matched". Maybe it's some kind of encoding issue. Try to compare length and if it is ok, try to leave only one line in the file and try this code:
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for (char ch : users[0].toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for (char ch : logline.toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
It should return equal lines of numbers like this:
7477889449505152
7477889449505152
Matched
Login line: JMX^1234
Text Line: JMX^1234
Also try to check out this answer: https://stackoverflow.com/a/4210732/6226118
Lets say I have CSV file like this:
Football Contest blabla bla,,,,,,,
Team number1,Team number2,Points team1,Points team2,Red cards
Sweden,France,1,2,"
Sweden,Brazil,3,5,2
Sweden,Germany,2,2,3
Sweden,Spain,3,5,"
And in this file I only want to print out the matches that got red cards. So in this example I would like to print:
Sweden - Brazil = 2 Sweden - Germany = 3
This is my current code, and Im stuck how to move on.
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String lines = br.readLine();
String result[] = lines.split(",");
do{
System.out.println();
}while((lines = br.readLine()) != null);
//String result[] = lines.split(",");
//System.out.println(result[1]);
br.close();
}catch (FileNotFoundException e){
System.out.println("File not found : "+ file.toString());
}catch (IOException e ){
System.out.println("Unable to read file: "+ file.toString());
}
EDIT I got helped with:
while (line != null) {
String result[] = line.split(",");
if (result.length == 5) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
But the problem I have now is that it still prints all because of the " in the csv file. Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
If you the index of red card and it looks like Integer, Then see for that index is integer or not if Yes the print 0,1 and 4
index[0]=Team number1
index[1]=Team number2
index[4]=red cards
Your try-catch block should look like this:
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
String result[] = line.split(",");
if (result.length == 5 && result[4].matches("[0-9]")) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
//close readers
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found : " + file.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + file.toString());
}
If there are trailing whitespaces in your file, you have to trim the String first: result[4].trim().matches("[0-9]") or use another regex: result[4].matches("\\d\\s")
Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
The problem with this is == tests for identity: it will compare if the reference in result[4] is the same reference as the constant in your source code. That expression will always be false. You need to check for equality, not identity:
if (Objects.equals(result[4], "1,2,3,4,5")) {
or
if (result[4] != null && result[4].equals("1,2,3,4,5")) {
or
if ("1,2,3,4,5".equals(result[4])) {
Note that Objects.equals() was (finally) added to the Java standard library in Java 8. Without it, you must guard against a NullPointerException before you call the .equals() method on an object. Traditionally I have preferred the last version because invoking the method on the string literal means I can be assured it is never null and will just work.
You can try like this
public class HelloWorld{
public static void main(String []args){
String str1= "Sweden,Brazil,3,5,4";
String str2="Sweden,Germany,2,2,3";
String str3="Football Contest blabla bla,,,,,,,";
String result1[]=str1.split(",");
String result2[]=str2.split(",");
String result3[]=str3.split(",");
if(result1.length>=5){
System.out.print(result1[0]+"-"+result1[1]+"="+result1[4]);
System.out.println();
}
if(result2.length>=5){
System.out.print(result2[0]+"-"+result2[1]+"="+result2[4]);
System.out.println();
}
if(result3.length>=5){
System.out.print(result3[0]+"-"+result3[1]+"="+result3[4]);
System.out.println();
}
}
}
try this:
do {
if (result[4] instanceof Integer) {
System.out.print(result[0]+"="+result[1]+"="+result[4])
}
} while ((lines = br.readLine()) != null);
So I am trying to extract a piece of code from a txtfile ,the start of the piece being indicated by "# EMPIRES" and the end being indicated by another string starting with a '#'. My program however never finds the start of the piece and keeps on going until it reaches the end of the file.
To try and find out what the problem was I tried first to print every line that it finds.
And here I encountered another problem. My code already stops finding new lines,long before
"# EMPIRES" is even reached.
public String getEmpirestxt(String fileName) {
Scanner sc;
try {
sc = new Scanner(new File(fileName));
String currentLine = sc.nextLine();
StringBuilder empiresText = new StringBuilder(currentLine);
while (!currentLine.startsWith("# EMPIRES")) {
currentLine = sc.nextLine();
System.out.println(currentLine);
}
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
return empiresText.toString();
} catch (FileNotFoundException ex) {
System.out.println("Landed_Titles.txt not found.");
}
return null;
}
The textfile itself :
https://www.wetransfer.com/downloads/a1093792d5ac54b6ccce04afecb9357f20140402095042/505fca
Here is my solution to your problem. I used newBufferedReader instead of the Scanner to read the file. This example works with Java 7.
public String getEmpirestxt2(String fileName) {
Charset charset = Charset.forName("ISO-8859-1");
Path filePath = Paths.get(fileName);
try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) {
String line = null;
// find the start of the piece
while ((line = reader.readLine()) != null && !line.equals(START)) {
}
System.out.println("START: " + line);
// getting the piece
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null && !line.startsWith(END)) {
sb.append(line);
}
System.out.println("END: " + line);
return sb.toString();
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
return null;
}
The constants in the method are:
private static final String START = "# EMPIRES";
private static final String END = "#";
I tested it with your file and it works fine. It also prints the starting and end points of the required piece:
START: # EMPIRES
END: # color={ 144 80 60 }
String currentLine = sc.nextLine();
you are starting reading from the next Line.
The condition:
while (sc.hasNextLine() && currentLine.charAt(0)!='#')
may terminate even if the file has more lines to read, because of the second predicate. If currentLine.charAt(0)!='#' is fales, the while loop ends. This does not mean there are no more lines to read.
In your second while loop you never set currentLine
This part:
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
should be:
do{
currentLine=sc.nextLine();
empiresText.append("\n").append(sc.nextLine());
}while(sc.hasNextLine() && currentLine.charAt(0)!='#');
Otherwise the line right after # EMPIRES won't be read and the code while loop will never stop because the currentLine is not getting updated.
Append currentLine instead of sc.nextLine() in the second while loop :
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
Otherwise you can use a single loop like below :
while (sc.hasNextLine()){
if(sc.nextLine().startsWith("# EMPIRES")){
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
}
}