I have done the reading and writing of the files, but I have a problem. I don't know why it shows only the last line of the files. In the part with reading the lines from Person.txt, when I get out of the while loop, I want to show the p.getName() for each line and it shows only the last line. How can I fix this?
here is my code:
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class ListaHobby {
String line="";
Hobby h = new Hobby();
Persoana p = new Persoana();
BufferedWriter bw = null;
ArrayList<Persoana> listOfPersons;
ArrayList<Hobby> listOfHobbies;
public void writeListaHobbies(){
try{
listOfPersons = new ArrayList<Persoana>();
FileReader file1 =new FileReader("Persoane.txt");
listOfHobbies = new ArrayList<Hobby>();
FileReader file2 = new FileReader("Hobby.txt");
BufferedReader br1 = new BufferedReader(file1);
BufferedReader br2 = new BufferedReader(file2);
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
//Person person = new Person(); // make a new person
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
System.out.println(p.getNume());
while((line2 = br2.readLine()) != null){
if(!line2.trim().contains("ID")){
String[] attributes = line2.split(";"); // split it at every ";"
// make a new person
h.setNume(attributes[1]);
h.setDescriere(attributes[2]);
h.setNrPers(attributes[3]);
h.setElemNecesar(attributes[4]);
listOfHobbies.add(h);
}
}
System.out.println(h.getNume());
FileWriter fw = new FileWriter("PersHobby.txt");
bw = new BufferedWriter(fw);
for(int i = 0;i < listOfPersons.size(); i++) {
//for(int j = 0 ; j < listOfHobbies.size();j++) {
if((p.getId())== (h.getId()))
p.addHobby(h);
String s = p.getNume() + " " +p.getPrenume() +
": " + h.getNume() + ", " + h.getNume();
System.out.println(s);
bw.write(s);
bw.newLine();
}
bw.close();
}
catch(IOException ex){
System.out.println("Error opening file.");
System.exit(1);
}
}
}
You keep adding the same person to your list. You need to create a new object at each iteration by uncommenting the commented line. Once you have done that, you can remove the class member (p) as it is not needed any longer because you store the persons in the ArrayList.
The same comment applies to the list of hobbies.
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
Persoana p = new Persoana(); // <~~~ you need to create a new person for each line
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
You are using the single instances of Person and Hobby to add to the respective lists. Instead, for each (unique?) ID found, create new Person, new Hobby and use them to add to the list.
p = new Person();
p.setXXX...
...
Similarly for Hobby.
h = new Hobby();
h.setXXX...
...
Unless you do this, you only be adding the latest found data to the same person and hobby objects to the lists.
You need to add people and hobbies when reading each line of the input file and iterate through both the people and hobbies when writing to file.
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class ListaHobby {
String line="";
Hobby h;
Persoana p;
BufferedWriter bw = null;
ArrayList<Persoana> listOfPersons;
ArrayList<Hobby> listOfHobbies;
public void writeListaHobbies(){
try{
listOfPersons = new ArrayList<Persoana>();
FileReader file1 =new FileReader("Persoane.txt");
listOfHobbies = new ArrayList<Hobby>();
FileReader file2 = new FileReader("Hobby.txt");
BufferedReader br1 = new BufferedReader(file1);
BufferedReader br2 = new BufferedReader(file2);
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
p = new Persoana(); // make a new person
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
System.out.println(p.getNume());
while((line2 = br2.readLine()) != null){
if(!line2.trim().contains("ID")){
String[] attributes = line2.split(";"); // split it at every ";"
h=new Hobby();
h.setNume(attributes[1]);
h.setDescriere(attributes[2]);
h.setNrPers(attributes[3]);
h.setElemNecesar(attributes[4]);
listOfHobbies.add(h);
}
}
System.out.println(h.getNume());
FileWriter fw = new FileWriter("PersHobby.txt");
bw = new BufferedWriter(fw);
for(int i = 0;i < listOfPersons.size(); i++) {
p=listOfPersons.get(i);
for(int j = 0 ; j < listOfHobbies.size();j++) {
h=listOfHobbies.get(j);
if(p.getId())== h.getId()))
p.addHobby(h);
String s = p.getNume() + " " +p.getPrenume() +
": " + h.getNume() + ", " + h.getNume();
System.out.println(s);
bw.write(s);
bw.newLine();
}
}
bw.close();
}
catch(IOException ex){
System.out.println("Error opening file.");
System.exit(1);
}
}
}
Related
I have a csv file and I have some data in it and I want to append a column in it. e.g:
Name,Age,Marks
Joe,15,1
Smith,20,2
I want to append that Marks Column through code. The problem I'm getting is
Name,Age,Marks
Joe,15
1
2
Smith,20
1
2
The data is getting written 2 times and also the on the first column (Except the first one). How can I prevent it from doing it ? I've been stuck in this problem from past 1 week
My code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class appendCol {
public static String appendingCol() {
String stringArray[] = {"Marks", "1", "2"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
sb.append(stringArray[i]);
}
String str = sb.toString();
return str;
}
public static void main(String[] args) throws IOException {
String line = "";
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {
while ((line = br.readLine()) != null) {
String newFileLine = line + "," + appendingCol();
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
}
}
With this as input in text1.csv:
Name,Age
Joe,15
Smith,20
I ran (very tightly adapted from your code):
static void tryStackOverflow () {
String line = "";
try {
BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv"));
BufferedReader br = new BufferedReader (new FileReader ("text1.csv"));
while ((line = br.readLine ()) != null) {
String newFileLine = line + "," + appendingCol ();
writer.write (newFileLine);
writer.newLine ();
}
writer.close ();
} catch (IOException excep) {
System.err.println ("Exception " + excep);
}
}
public static String appendingCol () {
String stringArray[] = { "Marks", "1", "2" };
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < stringArray.length; i++) {
sb.append (stringArray [i]);
}
String str = sb.toString ();
return str;
}
and that produced:
Name,Age,Marks12
Joe,15,Marks12
Smith,20,Marks12
Then it seems clear that stringArray should be be in the other method (your main method) and added to line by line. Your code also assumes there are as many lines as elements in that array. But disregarding that, I moved the array and eliminated the appendingCol method and ran this:
static void tryStackOverflow () {
String line = "";
String stringArray[] = { "Marks", "1", "2" };
int lineNum = 0;
try {
BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv"));
BufferedReader br = new BufferedReader (new FileReader ("text1.csv"));
while ((line = br.readLine ()) != null) {
String newFileLine = line + "," + stringArray [lineNum++];
writer.write (newFileLine);
writer.newLine ();
}
writer.close ();
} catch (IOException excep) {
System.err.println ("Exception " + excep);
}
}
which produced this:
Name,Age,Marks
Joe,15,1
Smith,20,2
The header needs to be handled separately from the values.
public static void main(String[] args) throws IOException {
Map<String, String[]> csvCol = new HashMap<String, String[]>();
String stringArray[] = { "1", "2" };
csvCol.put('Marks', stringArray);
String line = "";
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {
String headers = "";
String values = "";
String newFileLine ="";
bool isHeader=true;
while ((line = br.readLine()) != null) {
if(isHeader){
csvCol.forEach((k,v) -> {
headers = "," + k ;
});
newFileLine = line + headers ;
}else{
csvCol.forEach((k,v) -> {
values = "," + v ;
});
newFileLine = line + values;
isHeader = false;
}
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
}
This problem requires one more column to be appended to the original CSV. The Java implementation is longer in code. However, it is easy to write with the open-source package SPL under Java, as long as one sentence:
+
A
1
=file("temp.csv").export#wc(file("test1.csv").import#wc().(~|="Marks,1,2".split#c()(#)))
SPL provides JDBC for JAVA to call, save the above script as append.splx, and call the script file as a stored procedure in JAVA:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st=con.prepareCall("call append()");
st.execute();
…
Or directly execute the SPL string in SQL in JAVA:
…
st = con.prepareStatement("==file(\"temp.csv\").export#wc(file(\"test1.csv\")
.import#wc().(~|=\"Marks,1,2\".split#c()(#)))");
st.execute();
…
I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)
I know there are many similar questions here, but I still can't solve it. I can get all the results that I want. However, in the end, it still shows nullpointerexception. I don't know why. can anyone help?
public class PointGenterate {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
try{
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i <10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine();
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){
line = br.readLine();
if(line==" "){
System.out.print("empty");
}else{
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
the txt file format is like
{ "type": "Feature", "properties": { "id": 126.000000, "osm_id": 4851918786.000000, "name": "Moray House Library", "type": "library" }, "geometry": { "type": "Point", "coordinates": [ -3.180841771200988, 55.950622362732418 ] } },
this is one line. I have many lines, and actually this is just a test code. if it works. i want to write it as a method in a javaseverlet class. get the string coordinates and return it to my JS font-end.
There's a few issues with your code. In this section:
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine(); // here you read the first line in the file
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){ // here you check that it's not null (it's not, you read the first line OK)
line = br.readLine(); // here you read the second line (there is no second line, now line is null)
if(line==" "){ // now you check if the line is a space character (this is wrong for 2 reasons, that's not how you compare strings, and a space character is not an empty string)
System.out.print("empty");
}else{
data = line.split(",|:|[|]"); // here you call split() on line but line is null
}
When you checked if the string was empty, you did line == " " which is wrong for 2 reasons. First you cannot use == to compare strings - read this question for details on why not. Second, " " is a string that contains a space character. "" is an empty string.
When you want to check if a string is empty you can do it like this:
line.equals("")
or like this:
line.isEmpty()
Here's your code with a few small changes so that it runs without throwing an exception.
public class PointGenterate {
public static void main(String[] args) throws Exception {
try {
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i < 10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while((line = br.readLine()) != null){ // read the line and check for null
if(line.isEmpty()) { // is the line equal to the empty string?
System.out.print("empty");
} else {
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
I have some CSV file with the same column header.
I want to make them to one file.So I found something similar to me. Link is Merge CSV files into a single file with no repeated headers.
but I want to return the data as a String, but this code has no return.
I try to modify that. but I failed.
I want to put the data from several csv into one variable.
String[] headers = null;
String firstFile = "/path/to/firstFile.dat";
Scanner scanner = new Scanner(new File(firstFile));
if (scanner.hasNextLine())
headers[] = scanner.nextLine().split(",");
scanner.close();
Iterator<File> iterFiles = listOfFilesToBeMerged.iterator();
BufferedWriter writer = new BufferedWriter(new FileWriter(firstFile, true));
while (iterFiles.hasNext()) {
File nextFile = iterFiles.next();
BufferedReader reader = new BufferedReader(new FileReader(nextFile));
String line = null;
String[] firstLine = null;
if ((line = reader.readLine()) != null)
firstLine = line.split(",");
if (!Arrays.equals (headers, firstLine))
throw new FileMergeException("Header mis-match between CSV files: '" +
firstFile + "' and '" + nextFile.getAbsolutePath());
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
}
writer.close();
Here is what you might be looking for.
I have read two csv files and written into one.
Hope this is use full...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(new FileReader( "d:\\1\\2.csv"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("d:\\1\\good.csv"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("DONE Enjoy!!");
writer.close();
}
}
Or if you looking for a function which returns String combining two csv
public static String combineCSV() {
ArrayList<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(
"d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(
new FileReader("d:\\1\\2.csv"));
String s1 = null;
String s2 = null;
while ((s1 = br.readLine()) != null) {
list.add(s1);
}
while ((s2 = r.readLine()) != null) {
list.add(s2);
}
} catch (IOException e) {
e.printStackTrace();
}
String listWord;
StringBuffer objBuffer = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
listWord = list.get(i);
objBuffer.append(listWord);
objBuffer.append("\n");
}
System.out.println("DONE Enjoy!!");
System.out.println(objBuffer);
return objBuffer.toString();
}
Thank you!!!!
Enjoy Coding...
Another alternative is to use Open CSV library
import net.htmlparser.jericho.*;
#SuppressWarnings({ "serial", "unused" })
public class RenderToText extends JDialog {
static JTextArea _resultArea = new JTextArea(100, 100);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
private final static String newline = "\n";
int filename = 100;
String[] fileName = new String[filename];
public RenderToText(){
for (int i = 0; i < filename; i++) {
String fileName = "abc"+i+".txt";
// A File object to represent the filename
File f = new File(fileName);
f.delete();
}
_resultArea.setEditable(false);
//Starting to write files
try{
FileReader fr = new FileReader(
"C:\\Users\\user\\fypworkspace\\FYP\\Link\\abc.txt");
BufferedReader textReader = new BufferedReader(fr);
// for each URL, process the URL and render the HTML file
int numberofURL = 100;
String[] URL = new String[numberofURL];
int a;
// For each URL, assign one text file to store the contents
// for each URL, extract the URL contents
for (a = 0; a < numberofURL; a++) {
for (int i = 0; i < numberofURL; i++) {
URL[a] = textReader.readLine();
try{
try {
try {
// Render the text from the HTML file
String sourceUrlString = URL[a];
System.out.println("Using argument of \""
+ sourceUrlString + '"');
if (sourceUrlString.indexOf(':') == -1)
sourceUrlString = "file:" + sourceUrlString;
Source source = new Source(new URL(sourceUrlString));
String renderedText = source.getRenderer()
.toString();
_resultArea.append("\nSimple rendering of the HTML document:\n" + newline);
System.out.println(renderedText+ newline);
// Write the rendered text to a text file
String filename = ("abc" + i + ".txt");
Writer output = null;
String text = renderedText;
File file = new File(filename);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written"+ newline);
// Count the number of words available in the
// rendered text.
BufferedReader br = new BufferedReader(
new FileReader(
"C:\\Users\\user\\fypworkspace\\FYP\\abc"
+ i + ".txt"));
String line = "", str = "";
int count = 0;
while ((line = br.readLine()) != null) {
str += line + " ";
}
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
count++;
}
_resultArea.append("File has " + count + " words."+ newline);
} catch (UnknownServiceException ex) {
System.out.println("The following url cannot be processed"+ newline);
}
System.out.println("\n");
System.out.println("\n");
System.out.println("\n");
} catch (NullPointerException ex) {
System.out.println("End of URL");
System.exit(0);
}
}catch(IOException ex){
System.out.println("The following url cannot be processed due to the need to login");
}
}
}
}catch (IOException e1) {
}
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
this.setContentPane(content);
this.setTitle("TextAreaDemo B");
this.pack();
}
public static void main(String[] args) throws IOException {
JDialog win = new RenderToText();
win.setVisible(true);
}
}
This code extract the contents of a website. I have use append on the output, however the jtextarea does not come out. It cant run, but it CANT transfer the output to the jtextarea. What do i missing ?
You are running two loops
for (a = 0; a < numberofURL; a++)
for (int i = 0; i < numberofURL; i++)
with 100 steps each. Thus you're reading 10000 URLs from your input file. If there are not enough of them readline will return null and thus you'll exceptions (see also comment from extraneon). Get rid of the useless second loop.
Besides the errors in reading the files your textarea should display the output (and it does in my test). Therefore it seems that it lies within your read loop and the exception handling therein.
Note: please also consider the other comments from extraneon.
Agree with comment about static JTextArea. If you want to shere content you can use the same Document in two JTextAreas added in different places.