Converting a binary number to decimal from a file with whitespace - java

I am trying to convert binary numbers to decimal from a file. I am able to get the numbers to convert, however, in my text file, if I have more then one binary number in a line the code just skips it.
List<Integer> list = new ArrayList<Integer>();
File file = new File("binary.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
try {
list.add(Integer.parseInt(text,2));
}
catch (Exception ex) {
continue;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Here is the text file that I am using as well:
00100101
00100110 01000001
01100000
01111011
10010100 00100101
01101011
11000111 00011010
When I run my code I get: [37, 96, 123, 107]
The code skips the lines where there are two binary numbers.
I'm having trouble trying to be able to convert the integers and not use reader.readLine() in the while loop. Any help is greatly appreciated!

Split each line read by the while loop using text.split("\\s+"), and iterate the split values:
String text = null;
while ((text = reader.readLine()) != null) {
for (String value : text.split("\\s+")) {
try {
list.add(Integer.parseInt(value,2));
}
catch (Exception ex) {
continue; // should throw error: File is corrupt
}
}
}

This should do for when you have multiple values in one line.
You loop over the multiple values and add them separately.
try {
for (String s : text.split(" ") list.add(Integer.parseInt(s,2));
}
Also, like Andreas wrote it, it is not recommended to ignore Exceptions.

Related

Java ignore a specific symbol after another specific symbol

I have a .csv file. Data is divided by commas and I need to extract information out this file. Thing is if i just write this it works but partially:
String file = "FinalProject/src/Data.csv";
BufferedReader rd = null;
String line = "";
HashSet<String> platforms = new HashSet<String>();
try
{
rd = new BufferedReader(new FileReader(file));
rd.readLine();
while ((line = rd.readLine())!=null)
{
String [] arr = line.split("\"");
var words = new ArrayList<String>();
for(int i =0; i < arr.length;i++)
{
if(i % 2 == 0)
{
words.addAll(Arrays.asList(arr[i].split(",")));
}
else
{
words.add(arr[i]);
}
platforms.add(words.get(2));
}
}
}
catch (Exception e)
{
System.out.println("");
}
finally
{
try
{
rd.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
When I check the contents of Set and extract the same data out of the database created from this .csv file it shows difference. For example - my set has 38 values, when the database has 40, all of them are unique( nothing is repeated). I think the problem is caused by separation of data in .csv file with comma signs. Because some of these signs are inside of quotes and this probably causes a loss of the potential values that i need. Is there any solution to that problem? Or perhaps there is a more efficient way to deal with the comma sings inside of the quotes so that they are ignored?

Read file, one line at a time and run code

I have a file with text in this format:
text:text2:text3
text4:text5:text6
text7:text8:text9
Now what I want to do, is to read the first line, separate the words at the ":", and save the 3 strings into different variables. those variables are then used as parameter for a method, before having the program read the next line and doing the same thing over and over again.. So far I've got this:
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("C://Users//Patrick//Desktop//textfile.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also, I've tried this for separation (although not sure Array is the best option:
String[] strArr = sCurrentLine.split("\\:");
Use String[] parts = line.split(":"); to get an array with text, text2 etc. You can then loop through parts and call the method you want with each item in the list.
Your original split does not work, because : is not a special character in Regex. You only have to use an escape character when the split you are trying to achieve uses a special character.
More information here.

Remove duplicates from CSV file in eclipse

I have an assignment where i have to read a CSV file containing data with some repeated lines. How to remove the duplicate values and print only the unique values in Eclipse
The data is similar to this:-
1,Ron,1234,ABC,12
2,Harry,4125,DEF,14
3,Kent,1786,GHI,15
1,Ron,1234,ABC,12
2,Harry,4125,DEF,14
String csvFile = "csv.csv";
BufferedReader br = null;
String line = "";
HashSet<String> lines = new HashSet<>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (lines.add(line)) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It may help you
My suggestion is to use the following strategy:
1st step: create a HashMap http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
where you will save each line of the CSV you read. You will save in a hashmap because Hashmap will NOT accept a key that is like another. So, each line you will read, you will save in the hashmap as a KEY!
So, the logic is: Try to save the line you just read as a Key. IF it works, print that line. If it didn't work, discard the line and read the next one.
Got it?
2nd step:
Use a BufferedReader http://docs.oracle.com/javase/7/docs/api/index.html?java/io/BufferedReader.html to read line by line of the CSV.
Get each line of the CSV with the BufferedReader with readLine().
It will save the line you are reading in a String
That's it.
So, here is the overview of the entire code:
1- Read each line of the code with BufferedReader.readLine()
2- Get that string you got from readLine and try to add to your Hashmap as the Key of the hashmap: if it works, print the String. If it doesn't work, discard the string;
3- Read the next line.

Reading from a text file with spaces and then putting into arrayList

I have spent the last week trying to figure out how to make this stupid code work. I have managed to get everything to work except for reading from my text file. It can read an individual integer on a line, but when given a line with multiple integers separated by spaces, it freaks out. Now I've gone and tried to fix it and the code won't even compile anymore. Only one line is causing problems.
I'm not good at coding, so I don't know where to begin. Yes, I've looked this up online. Yes, I've checked the forums. Yes, I have tried multiple different methods to make this work....
How do I fix this?? :(
ArrayList<Integer> list = new ArrayList<Integer>();
// the above line is in a different method in the same class, but it's relevant here
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// I want the following line to read "218 150 500 330", and to store each individual integer into the list. I don't know why it won't work :(
list.add(Integer.parseInt(src.next().trim()));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//print out the list
System.out.println(list);
Thank you for the help! I'm sure that I'm just missing something really simple...
You can use a Scanner(String) like
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
Of course, your entire method could be simplified by using a try-with-resources Statement and the diamond operator and just Scanner(File) like
public static void main(String[] args) {
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(file);) {
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
} catch (Exception e) {
e.printStackTrace();
}
// print out the list
System.out.println(list);
}
Do this inside the while loop
String[] individualArray = text.split(" ");//note space
for(String individual:individualArray){
yourList.add(individual);//You need to parse it to integer here as you have already done
}
In the above code, individualArray will contain each individual integers that are separated by space. And inside the for loop each string needs to be parsed to integer and then added to your list
try this :
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// you need only this for loop in you code.
for (String value : text.split(" ")) { // get list of integer
if(!value.equals("")) // ignore space
list.add(Integer.parseInt(value)); // add to list
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
// print out the list
System.out.println(list);
}

Merging csv file

Please help me in java code. I have 2 CSV FILE
a.csv contains "zip","name","place"
b.csv contains "zip","latitude","longitude"
I need to merge the following columns with the same zip and save in another csv file
output.csv file will be:
"zip","name","place","latitude","longitude"
how am i going to code this? thank you.
I have read this a.csv but i dont know how to merge.
Here's my code in reading my first csv file
public class Merge{public static void main(String[]args ) throws Exception {
String csvFile ="a.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try{
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] cFile = line.split(cvsSplitBy);
System.out.println("" + cFile[1] + " " + cFile[2] + " ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System. out. println("Done");
}
}
I think you should write the below logic to achieve this. This is just an idea.. go ahead and implement if you get any error in any specific area. You ware welcome to get back with your questions.
Read csv 1, populate an array (array 1)
Read csv 2, populate another array (array 2)
Loop both the array check the zip and merge in 3rd array.. something like below
for(loop over array 1)
// get the zip from array1
for(loop over array 2)
// get the zip from array2
if(zip1 == zip2)
then merge and put the data in another array(array3) and break this loop
Write this array3 in a new csv file

Categories