I am trying to write data to CSV file.
The string value which starts with - is getting converted to #NAME? automatically when i open csv file after writing. e.g. If i write test it displays correctly but when i write -test the value would be #NAME? when i open csv file. It is not a code issue but csv file automatically changes the value which starts with - to error(#NAME?). How can i correct this programmatically. below is the code,
public class FileWriterTest {
public static void main(String[] args) {
BufferedWriter bufferedWriter = null;
File file = new File("test.csv");
try {
bufferedWriter = new BufferedWriter(new FileWriter(file));
List<String> records = getRecords();
for (String record : records) {
bufferedWriter.write(record);
bufferedWriter.newLine();
}
bufferedWriter.flush();
System.out.println("Completed writing data to a file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null)
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static List<String> getRecords() {
List<String> al = new ArrayList<String>();
String s1 = "test";
String s2 = "-test";
al.add(s1);
al.add(s2);
return al;
}
}
Could you please assist?
It's a problem with excel. When you open a CSV file in excel it tries to determine cell type automatically which usually fails. The CSV file is alright the editor is not ;)
You can either right click on the field, select Format Cell and there make it a text file (and you might need to remove the automatically inserted '=' sign). Or you can open the CSV file by going into Data - From Text/CSV and in the wizard select the proper column types.
In the formal CSV standard, you can do this by using quotes (") around the field value. They're a text delimiter (as opposed to other kinds of values, like numeric ones).
It sounds like you're using Excel. You may need to enable " as a text delimiter/indicator.
Update: If you double-click the .csv to open it in Excel, even this doesn't work. You have to open a workbook and then import the CSV data into it. (Pathetic, really...)
I got a relatively old version of Excel (2007), and the following works perfectly:
Put the text between double quotes and preceed it with an equal sign.
I.e., -test becomes ="-test".
You file will therefore look like this:
test1,test2,test3
test4,="-test5",test6
UPDATE
Works in Excel-2010 as well.
As Veselin Davidov mentioned, this will break the csv standard but I don't know whether that's a problem.
Related
how do I open the excel file located inside my project?
I would like to press a jbutton and open file1
What would you like to do with it? If you just want to handle the data of the Excel-file, I would export my Excel-file to a csv-file (in Excel 2016: File > Export > Change File Type > CSV (Comma delimited)).
The delimiter used for separating data depends on your system settings (mine is set on semicolon to eliminate annoying situations with commas in the cells).
The advantage of a CSV-file is that you can handle the file as any other text file.
Inside the actionPerformed-method of your JButton, you can open the file using:
try (Scanner sc = new Scanner(new File("my_csv_file.csv"))) {
// do anything you want with the file using the scanner object
// for example, print all data to the screen:
// make sure you import java.util.Scanner, java.io.File and java.io.FileNotFoundException
// and catch a FileNotFoundException or throw it to be handled anywhere else
while (sc.hasNextLine()) {
String data[] = sc.nextLine().split(";");
for (String s : data) {
System.out.print(s + "\t");
}
System.out.println();
}
}
I'm trying to use this library commons-csv (1.5) for generating the csv file, i've make a simple program for seeing the result :
String SAMPLE_CSV_FILE = "./sample.csv";
try (
BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL
.withHeader("ID", "Name", "Designation", "Company"));
) {
csvPrinter.printRecord("1", "Name1 ", "CEO", "Google");
csvPrinter.printRecord("2", "Name2", "CEO", "Microsoft");
csvPrinter.flush();
}
My CSV is well generated but the header and the data isnt separated in each column, When I open the CSV file, I see all the data and header in the first column
I dont found yet the good CSVFormat, how to separate them ?
The selected answer does not really show how you can make sure that comma is set as the delimiter.
To tell excel that comma should be used as a delimiter, Print printer.printRecord("SEP=,"); as the first record in your file. its a command that excel understands and it will not show in your file output.
try (CSVPrinter printer = new CSVPrinter(new FileWriter("file.csv"),CSVFormat.EXCEL)) {
printer.printRecord("SEP=,"); //this line does the margic.
printer.printRecord("Column A","Column B","Column C");
} catch (IOException ex) {
}
When I run your program, I get all the columns separated by comma's as expected. If you're using Excel to open the file, make sure you have selected the comma as the delimiter instead of the tab.
I have a simple write method using RandomAccessFile to write an ArrayList of Strings in a *.bin file. Depending on user input, the size of the ArrayList is going to change after every user access. This is the only method that writes to this file.
#FXML protected void writeToFile(){
try(RandomAccessFile file = new RandomAccessFile(fileName, "rw")){
// file.setLength(0);
file.seek(0);
file.writeUTF(wordsArrayList.toString());
file.close();
}catch (IOException e){
System.out.println("error writing from writeToFile()");
}
}
How can I clear the contents of the file (not delete the file and create a new one) using RandomAccessFile before writing to it again in order to avoid *.bin files like below? Setting the length to zero doesn't seem to work.
I wrote a program that reads from a text file using Java. The file has 1 column with a lot of integer values and each value is being added to an array list. However, when I print the array list, between each number I am getting an empty entry. For example if in text file I have:
4
55
I am getting:
1 : ÿþ4 (Also I do not know what this weird character is)
2 :
3 : 555
Code:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile {
public static void main(String[] args) {
try
{
Scanner input = new Scanner("ReadingFile.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
ArrayList numbers = new ArrayList();
int i=1;
while (input.hasNextLine()) {
String line = input.nextLine();;
numbers.add(line);
System.out.println(i + " : " + line);
i++;
}
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
I tried to avoid using the arraylist and just do :
System.out.println(i + " " + line);
however this problem is still there so I am guessing that it is not an ArrayList problem.
Provided your text file is actually a good text file, it could be a character encoding thing. You need to provide the correct character set to your scanner in its constructor. So change the line:
input = new Scanner(file);
Into something like:
String charset = "UTF-8";
input = new Scanner(file, charset);
Ofcourse, you need to figure out which character set your file is actually stored as and use that one. I do UTF-8 here only as an example.
OK, the problem is that you're actually reading binary from an excel file, hence the strange characters. If you want to read an excel file directly, then use a library such as JXL (http://jexcelapi.sourceforge.net/) - here's a good tutorial for using that API: http://www.vogella.com/tutorials/JavaExcel/article.html
Otherwise, you would want to save export your excel file to CSV format and read the file with your code.
weird chars should be writeUTF prefix or BOM. so, depends on how you write the file, reading method can be different.
if you write file with DataOutputStream and call writeUTF, then you should read the file with readUTF
if it is a simple text file that was written by a text program, like notepad++, I suggest call trim() function for every line.
Looks like your file is UTF-16. These two characters are the Byte order mark of UTF-16.
You must specify that when constructing your Scanner.
final Scanner scanner = new Scanner(file, "UTF-16");
If you don't have Notepad++ (text editor) download it. Open your generated text file using it.
Do find/Replace and populate the fields and check the settings by looking at the image below. then press Replace All. And then save your file. Your text file will be clean.
I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.
import java.io.*;
class ModifyXML {
public void readMyFile(String inputLine) throws Exception
{
String record = "";
File outFile = new File("tempFile.tmp");
FileInputStream fis = new FileInputStream("InfectiousDisease.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
while ( (record=br.readLine()) != null )
{
if(record.endsWith("<add-info>"))
{
out.println(" "+"<add-info>");
out.println(" "+inputLine);
}
else
{
out.println(record);
}
}
out.flush();
out.close();
br.close();
//Also we need to delete the original file
//outFile.renameTo(InfectiousDisease.xml);//Not working
}
public static void main (String[] args) {
try
{
ModifyXML f = new ModifyXML();
f.readMyFile("This is infectious disease data");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thanks
First delete the original file and then rename the new file:
File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");
if(inputFile.delete()){
outFile.renameTo(inputFile);
}
A good method to rename files is.
File file = new File("path-here");
file.renameTo(new File("new path here"));
In your code there are several issues.
First your description mentions renameing the original file and adding some text to it. Your code doesn't do that, it opens two files, one for reading and one for writing (with the additional text). That is the right way to do things, as adding text in-place is not really feasible using the techniques you are using.
The second issue is that you are opening a temporary file. Temporary files remove themselves upon closing, so all the work you did adding your text disappears as soon as you close the file.
The third issue is that you are modifying XML files as plain text. This sometimes works as XML files are a subset of plain text files, but there is no indication that you attempted to ensure that the output file was an XML file. Perhaps you know more about your input files than is mentioned, but if you want this to work correctly for 100% of the input cases, you probably want to create a SAX writer that writes out all a SAX reader reads, with the additional information in the correct tag location.
You can use
outFile.renameTo(new File(newFileName));
You have to ensure these files are not open at the time.