jtextarea does not pop out - java

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.

Related

How to get data from a CSV file and place it in a list

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:)

Dealing with txt file via split(), says Nullpointerexception

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();
}
}
}

Java - Trying to output to a file where if the user's login is there only replace the balance

My program is basically a user's name, and balance, this is stored in a file, when the user updates their profile, I want their balance to update too, but not their name, as they already have it in the file.
The name and balance are split with a comma. In the file it is displayed like this:
Stacey,0.02
(The name is actually a randomly generated number+letter string, but I thought I'd keep it simple here.)
When I try to write to the file with this code, it doesn't write anything.
Code:
btnSaveUserid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = txtUserid.getText().toString();
String balance = beedcoin1Balance.getText().toString();
File file = new File("d:/users/joel/desktop/code/usersid.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("d:/users/joel/desktop/code/usersid.txt"));
List<String> terms = new ArrayList<String>();
List<String> ttlBalance = new ArrayList<String>();
while ((sCurrentLine = br.readLine()) != null) {
String[] ar = sCurrentLine.split(",");
String userid = ar[0];
terms.add(userid);
System.out.println(terms);
}
if(terms.contains(text)) {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine());
String line = scanner.nextLine();
String[] ar = line.split(",");
String userid = ar[0];
String bdcv1val = ar[1];
int lineNum = 0;
lineNum++;
if(line.equals(userid)) {
Path path = Paths.get("d:/users/joel/desktop/code/usersid.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replace(txtUserid.toString(), txtUserid.toString());
Files.write(path, content.getBytes(charset));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
}
else {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
} catch (IOException el) {
el.printStackTrace();
} finally {
try {
if(br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It all takes place in a button's action listener, and this code outputs the "Successfully printed to file" but doesn't actually print it to the file. I'm honestly perplexed, any help would be greatly appreciated.

add some elements from 2 txt files into a third file

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);
}
}
}

JTextArea does not show up

import net.htmlparser.jericho.*;
import java.util.*;
import java.awt.BorderLayout;
import java.io.*;
import java.net.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class RenderToText extends JFrame {
static JTextArea _resultArea = new JTextArea(100, 100);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
private final static String newline = "\n";
public RenderToText(){
_resultArea.setEditable(false);
//Starting to write files
try{
FileReader fr = new FileReader(
"C:\\Users\\user\\fypworkspace\\FYP\\abc.txt");
BufferedReader textReader = new BufferedReader(fr);
// for each URL, process the URL and render the HTML file
int numberofURL = 11;
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);
_resultArea.append(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();
_resultArea.append("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\\TextRenderer\\abc"
+ i + ".txt"));
String line = "", str = "";
int count = 0;
while ((line = br.readLine()) != null) {
str += line + " ";
}
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
#SuppressWarnings("unused")
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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
public static void main(String[] args) throws IOException {
JFrame win = new RenderToText();
win.setVisible(true);
}
}
This code suppose to display a JTextArea with the outputs of this program. This program render html page and extract their contents. Its wierd since i can run it and display the result in the console, however, i could not display it in Jtext Area. Where do i missing?
The file to be printed suppose to be this line of code :
_resultArea.append(renderedText+ newline);
However, upon execution, the JTextArea does not appear.
Set it visible _resultArea.setVisible(true);
And it looks like you dont actually add the GUI components until after your process your data. Not sure if that is what you want or not.

Categories