I have a problem. I want to create a new CSV file from CSVWriter and my whole Array is set into the one cell.
This is my java code:
StringWriter s = new StringWriter();
#SuppressWarnings("deprecation")
CSVWriter writer = new CSVWriter(s, '\t');
String[] entries = new String[3];
entries[0] = "Test";
entries[1] = "Test";
writer.writeNext(entries);
writer.close();
String finalString = s.toString();
System.out.println(finalString);
I get the output like this: "first" "second" "third"
and my CSV is :
but I want to be like this:
Your code is OK, the problem is you open the CSV file by Excel with default settings.
If you open the CSV file with Notepad, it will look like this:
"Test" "Test"
And if you still want to open it with Excel, you are supposed to open it by following steps:
Create a new sheet.
Select Data > From Text File.
Select file (write.csv) to be imported.
Click Finish.
Related
Currently I am trying to use PDFBox in Eclipse to run multiple PDF files in a folder through a text reader that will extract certain terms and output them into a text file that I will then convert to an excel sheet. Currently I have the program and it works correctly for a single PDF file:
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("ADE_acetylfuranoside_120319_pfister.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
//..."Actual code that extracts text"...
PrintStream o = new PrintStream(new File("output.txt"));
PrintStream console = System.out;
System.setOut(o);
System.out.println(finalSheet);
my problem is that I want to run 500 PDFs in one folder through this program on eclipse rather than putting in the name of each one individually. I also want it to output like:
Name1, Number1, ID1
Name2, Number2, ID2
but I think the way it is written now it will just overwrite line number one if I run multiple PDFs though it.
Thanks for the help!
For the first part, you could just use the File class with a FileFilter:
// directoryName could be as simple a "."
File folder = new File(directoryName);
File[] listOfFiles = folder.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".pdf");
}
});
This gives you an array of File objects of all the files in a particular folder/directory. Now you can loop through it with pretty much the code you have.
On the output side, you'll likely want to correlate the output with the input. I'm a bit confused by your code and I'm guessing you'd just like an output file for each input file. So, perhaps, something like:
// index is the value you used to loop through the `listOfFiles` array
try( FileWriter fileWriter = new FileWriter(listOfFiles[index].getName() + ".output.txt" ) ) {
fileWriter.write( // the String text you want in the file );
}
This creates a file named (as taken from your example) "ADE_acetylfuranoside_120319_pfister.pdf.output.txt". Obviously this could change. In this case a new file is created for each input file.
i want to add data inside of an existing json file..
this is my code:
JsonWriterWithGui(){
if(ae.getSource() == btn_submit){
String lname = (String)lbl_name.getText().toString();
String ladd = (String)lbl_add.getText().toString();
String lcontact = (String)lbl_contact.getText().toString();
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
jsonFileWriter.write(jsonObject.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
this code is already working. but I am trying to update a json file that already exists.
This is a bit of a guess because the problem you're having isn't entirely clear from the question, but if you're finding that your writes are overwriting instead of appending then try changing this line:
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
...to this:
FileWriter jsonFileWriter = new FileWriter("E:\\"+tsave+".json", true);
You see, FileWriter is backed by FileOutputStream, which takes a boolean argument saying whether new content should be appended or not. This boolean is false by default so if you want to append then you need to explicitly say so.
The following code writes a string to a specific file.
String content = "Text To be written on a File";
File file = new File("c:/file.txt");
FileOutputStream foutput = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] c = content.getBytes();
foutput.write(c);
foutput.flush();
foutput.close();
I want to use this code in a Jbutton so every time the user clicks it, it writes the string to a NEW text file NOT OVERWRITE the existed one. I tried to do but I couldn't get the result.
Thank you in advance.
There's a couple of different ways you can get this result, it really depends on the application. The two easiest ways to do this would to be either:
Append the current timestamp to the file name
Use the File API to create a "temp file" in the directory, which is guarenteed to have a unique name
Option 1:
String baseDir = "c:/";
File newFile = new File(baseDir, "file_" + System.currentTimeMillis() + ".txt");
// do file IO logic here...
Option 2:
String baseDir = "c:/";
File newFile = File.createTempFile("file", ".txt", new File(baseDir));
// do file IO logic here...
If you want to write it to a new file, you have to create a new file. The name of the text file is always file.txt in your case.
Try this:
private int filecounter = 0; // this is the member of your class. Outside the function.
//inside your function
File file = new File("c:/file" + Integer.(filecounter).toString() + ".txt");
// you do something here.
filecounter++;
This way, your files will be stored as file0.txt, file1.txt etc.
Let's say that I have a TreeMap and I want to take all values for a key, make a file with these, pass the file to another process loop and do this for every map key, so I always have to use the same file but its content must be replaced every time for each key.
What I do is:
PrintWriter writeRatings = new PrintWriter("ratings.txt", "UTF-8");
TreeMap<Integer, ArrayList<Rating>> ratings = new TreeMap<Integer, ArrayList<Rating>>();
-->
for(Integer clID:ratings.keySet()){
ArrayList<Rating> ratingGroup = ratings.get(clID);
for(Rating r:ratingGroup){
witer.println(r.toString());
}
}
writer.flush();
writer.close();
With this, I get a file with all the data for each map key. Can you suggest how can I get only the data from the current key each time in the file?
If you want to use the same file and just append lines to it, use a FileWriter and set the append mode to true
PrintWriter writer = new PrintWriter(new FileWriter("filename", true));
This will append lines to the file, instead of over writing the file. This way, different processes can use the same file and keep on adding new data to the file
So what worked for me was to include this line into the for loop in the position of the arrow in the main question post:
PrintWriter writer = new PrintWriter(new FileWriter("filename"));
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.