'How to add a new column to a csv file using Apache Commons?
I have a csv file that look like this:
name,age,total
xyz,22
abc,20
After processing the csv file should look like this:
name,age,total
xyz,22,100
abc,20,102
After running this code:
public class Converter {
public static void main(String[] args) throws IOException {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(Constants.SAMPLE_CSV_FILE));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
csvPrinter.print(100);
csvPrinter.print(102);
csvPrinter.close();
}
}
the output csv file becomes like this:
100
102
I want 100 and 102 to come under the total column. How can I do this?
Solution 1:[1]
First of all, you shouldn't override your existing file. Hence, use the appending argument on the FileWriter constructor:
FileWriter pw = new FileWriter("C:\\exampleFile.csv",true);
Second, as you can see in your result, the CSVPrinter goes through your file by rows. If you want to add a new column, you actually need to iterate over each row and insert the new column's row data on every iteration, as explained thoroughly here
Solution 2:[2]
You are almost there. It is hard to tell what you want to do, from the way your question is phrased. Do you want to display the text Receiving Data, as in that specific text, but in binary? Or did you want to take the line that has the two asterisks on either side and convert that data to binary? I will assume the latter.
By the "line surrounded by double asterisks," I specifically mean your code
byte []arr = System.Text.Encoding.ASCII.GetBytes(data);
As we know, binary is 0s and 1s. Each zero and each one is a bit, and each element of the array arr is a byte, which is always 8 bits long (at least, in the ASCII encoding, it is). Binary is what is known as a base-2 number system.
Per the question asked and answered over here on another Stack Overflow question, for each individual byte in your array, arr, you can represent it in binary via the following:
string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0');
As per the Microsoft documentation, the specific overload of ToString used is one that takes the current element of the byteArray, and represents it as a string in Base 2 which is binary.
The PadLeft method then pads it on then left with zeros in case the byte you are converting cannot be represented with 8 binary digits.
Let's create a new class in our project, say ByteToBinaryConverter and let's make it a static class. Furthermore, let's make our conversion method an extension method of byte, so that we can use it in a fluent (easy-to-read code) manner:
namespace serialchannel
{
public static class ByteToBinaryConverter
{
public static string ToBinaryString(this byte byteToConvert)
{
return Convert.ToString(byteToConvert, 2).PadLeft(8, '0');
}
}
}
Now, let's use the method in your SendButton_Click event handler method. I am going to repeat the code of that method here, with /* ... */ meaning ignore everything else, and calling our new method:
namespace serialchannel
{
public static class ByteToBinaryConverter
{
public static string ToBinaryString(this byte byteToConvert)
{
return Convert.ToString(byteToConvert, 2).PadLeft(8, '0');
}
}
public class Form1 : Form
{
/* ... rest of class ... */
private void SendButton_Click(object sender, EventArgs e)
{
var data = userInputTextBox.Text;
sport.Write(data);
var arr = System.Text.Encoding.ASCII.GetBytes(data);
var textToBeDisplayed = "";
foreach(var element in arr)
{
textToBeDisplayed += element.ToBinaryString();
}
displayedTextBox.AppendText(Environment.NewLine + "sent: " + textToBeDisplayed);
}
/* ... rest of class ... */
}
}
Notice the use of the var keyword instead of explicit data types. This makes use of Local variable type inference features of C# 3.0. Using the var keyword saves you from having to use explicit types in your code for variables. The C# compiler can figure it out based on what data you are initializing the variable with.
If you want to use explicit types, then I suggest the following variation of the code:
namespace serialchannel
{
public static class ByteToBinaryConverter
{
public static string ToBinaryString(this byte byteToConvert)
{
return Convert.ToString(byteToConvert, 2).PadLeft(8, '0');
}
}
public class Form1 : Form
{
/* ... rest of class ... */
private void SendButton_Click(object sender, EventArgs e)
{
string data = userInputTextBox.Text;
sport.Write(data);
byte[] arr = System.Text.Encoding.ASCII.GetBytes(data);
string textToBeDisplayed = "";
foreach(byte element in arr)
{
textToBeDisplayed += element.ToBinaryString();
}
displayedTextBox.AppendText(Environment.NewLine + "sent: " + textToBeDisplayed);
}
/* ... rest of class ... */
}
}
Above, I am using all lowercase versions of the type names; i.e., I am saying string not String as you have it. There really is no appreciable difference but it looks cleaner this way, in my opinion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GalAbra |
| Solution 2 | Dr. Brian Hart |
