Can someone help me to resolve my issue?
I have problem that BufferedWriter does not write to text file.
Program compiles without errors.
int number_of_line_to_delete_in_file = 0,number_of_all_lines = 0;
System.out.println("Trimmer - Logów pocztowych");
System.out.println("Rafał Biel v0.5");
try {
File file_reader = new File("src/log.txt");
System.out.println("Lokalizacja pliku LOG: " + file_reader.getAbsolutePath());
File file_saver = new File("src/logTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(file_reader));
BufferedWriter writer = new BufferedWriter(new FileWriter(file_saver));
LineNumberReader lnr = new LineNumberReader(reader);
String line_to_delete = "aaa";
String checked_line,line_counter;
while ((line_counter = lnr.readLine()) != null){
if(line_counter.equals(line_to_delete)) {
number_of_line_to_delete_in_file++; // sprawdzenie ilośći linii do usunięcia
}
number_of_all_lines++;// sprawdzenie ilośći wszystkich linii w pliku
}
System.out.println("W pliku znajduje się " + number_of_all_lines + " lini, w tym do usunięcia " + number_of_line_to_delete_in_file + " linii.");
while((checked_line = reader.readLine()) != null) {
String trimmed_line = checked_line.trim();
if(trimmed_line.equals(line_to_delete)) continue;
writer.write("TEST");
} // składnia odpowiadająca za usunięcie napisu z pliku.
writer.close();//zamknięcie zapisu
reader.close();//zamkniecia odczytu
boolean successful = file_saver.renameTo(file_reader);
System.out.println("Pomyślnie zakończyłem pracę " + successful);
}catch (Exception e){
System.err.println("Błąd: " + e.getMessage());
}
File is read, but when I try to open the file saved in Temp the file is empty
Problem is that you are reading the whole file in first while loop. Your file pointer has already reached at EOF. Now you are again trying to read that file in next while loop. Since pointer is already at EOF, it will return null and your code will never go inside second while loop.
Below is dirty way to validate my comments. I am reopening your log.txt file to reset the pointer. It is not efficient but points to the mistake.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
public class TestMainResuse {
public static void main(String[] args) throws Exception
{
TestMainResuse t = new TestMainResuse();
t.test();
}
public void test() throws IOException{
int number_of_line_to_delete_in_file = 0,number_of_all_lines = 0;
System.out.println("Trimmer - Logów pocztowych");
System.out.println("Rafał Biel v0.5");
try {
File file_reader = new File("src/log.txt");
System.out.println("Lokalizacja pliku LOG: " + file_reader.getAbsolutePath());
File file_saver = new File("src/logTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(file_reader));
BufferedWriter writer = new BufferedWriter(new FileWriter(file_saver));
LineNumberReader lnr = new LineNumberReader(reader);
String line_to_delete = "aaa";
String checked_line,line_counter;
while ((line_counter = lnr.readLine()) != null){
if(line_counter.equals(line_to_delete)) {
number_of_line_to_delete_in_file++; // sprawdzenie ilośći linii do usunięcia
}
number_of_all_lines++;// sprawdzenie ilośći wszystkich linii w pliku
}
// System.out.println("W pliku znajduje się " + number_of_all_lines + " lini, w tym do usunięcia " + number_of_line_to_delete_in_file + " linii.");
System.out.println(number_of_all_lines);
reader.close();
reader = new BufferedReader(new FileReader(file_reader));
while((checked_line = reader.readLine()) != null) {
System.out.println("In second while loop");
String trimmed_line = checked_line.trim();
if(trimmed_line.equals(line_to_delete)) continue;
writer.write("TEST");
} // składnia odpowiadająca za usunięcie napisu z pliku.
writer.close();//zamknięcie zapisu
reader.close();//zamkniecia odczytu
boolean successful = file_saver.renameTo(file_reader);
System.out.println("Pomyślnie zakończyłem pracę " + successful);
}catch (Exception e){
e.printStackTrace();
}
}
}
I'm going to pass my data from MongoDB to Neo4j.
So, I exported my MongoDB documents in .csv. As you can read here I have a problem with the array uniform.
So I wrote a java program to fix this problem.
Here is the .csv exported from MongoDB (note the different about uniform array):
_id,official_name,common_name,country,started_by.day,started_by.month,started_by.year,championship,stadium.name,stadium.capacity,palmares.first_prize,palmares.second_prize,palmares.third_prize,palmares.fourth_prize,average_age,squad_value,foreigners,uniform
0,yaDIXxLAOV,WWYWLqPcYM,QsVwiNmeGl,7,9,1479,oYKGgstIMv,qskcxizCkd,8560,10,25,9,29,16,58,6,"[""first_colour"",""second_colour"",""third_colour""]"
Here is how it must be to import in Neo4j:
_id,official_name,common_name,country,started_by.day,started_by.month,started_by.year,championship,stadium.name,stadium.capacity,palmares.first_prize,palmares.second_prize,palmares.third_prize,palmares.fourth_prize,average_age,squad_value,foreigners,uniform.0,uniform.1,uniform.2
0,yaDIXxLAOV,WWYWLqPcYM,QsVwiNmeGl,7,9,1479,oYKGgstIMv,qskcxizCkd,8560,10,25,9,29,16,58,6,first_colour,second_colour,third_colour
My code works, but I have to convert 500k line of the .csv file and the program it is too much slow(it's still working after 20 minutes :/):
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class ConvertireCSV {
public static void main(String[] args) throws IOException {
FileReader f;
f=new FileReader("output.csv");
BufferedReader b;
b=new BufferedReader(f);
String firstLine= b.readLine();
int uniform = firstLine.indexOf("uniform");
firstLine=firstLine.substring(0, uniform);
firstLine = firstLine + "uniform.0,uniform.1,uniform.2\n";
String line="";
String csv="";
while(true) {
line=b.readLine();
if(line==null)
break;
int u = line.indexOf("\"[");
line=line.substring(0, u);
line=line + "first_colour,second_colour,third_colour \n";
csv=csv+line;
}
File file = new File("outputForNeo4j.csv");
if(file.createNewFile()) {
PrintWriter pw = new PrintWriter(file);
pw.println(firstLine + csv);
System.out.println("New file \"outputForNeo4j.csv\" created.");
pw.flush();
pw.close();
}
}
}
How can I make it faster?
Okay some basic ways to improve your code:
Make sure that your variables got the minimal scope required. If you don't need line outside your loop, don't declare it outside your loop.
Concatenation of simple strings is in general slow. Use a StringBuilder to speed things to there.
Why are you buffering the string anyway? Seems like a waste of memory. Just open the output stream to your target file and write the lines to the new file as you process them.
Examples:
I don't think you need a example on the first point.
For the second things could look like this:
...
StringBuilder csv = new StringBuilder();
while(true) {
...
csv.append(line);
}
...
if(file.createNewFile()) {
...
pw.println(firstLine + csv.toString());
...
}
For the third point the rewriting would be a little more extensive:
public static void main(String[] args) throws IOException {
FileReader f;
f=new FileReader("output.csv");
BufferedReader b;
b=new BufferedReader(f);
String firstLine= b.readLine();
int uniform = firstLine.indexOf("uniform");
firstLine=firstLine.substring(0, uniform);
firstLine = firstLine + "uniform.0,uniform.1,uniform.2\n";
File file = new File("outputForNeo4j.csv");
if(!file.createNewFile()) {
// all work would be for nothing! Bailing out.
return;
}
PrintWriter pw = new PrintWriter(file);
pw.print(firstLine);
while(true) {
String line=b.readLine();
if(line==null)
break;
int u = line.indexOf("\"[");
line=line.substring(0, u);
line=line + "first_colour,second_colour,third_colour \n";
pw.print(line);
}
System.out.println("New file \"outputForNeo4j.csv\" created.");
pw.flush();
pw.close();
b.close()
}
csv=csv+line;
string concatenation is expensive operation. I would suggest using bufferedWriter.
something like this:
FileReader f;
f=new FileReader("output.csv");
BufferedReader b;
BufferedWriter out;
b=new BufferedReader(f);
try{
out = new BufferedWriter(new FileWriter("outputForNeo4j.csv"));
} catch(Exception e){
//cannot create file
}
System.out.println("New file \"outputForNeo4j.csv\" created.");
String firstLine= b.readLine();
int uniform = firstLine.indexOf("uniform");
firstLine=firstLine.substring(0, uniform);
firstLine = firstLine + "uniform.0,uniform.1,uniform.2\n";
String line="";
String csv="";
out.write(firstLine);
while(true) {
line=b.readLine();
if(line==null)
break;
int u = line.indexOf("\"[");
line=line.substring(0, u);
line=line + "first_colour,second_colour,third_colour \n";
out.write(line);
}
out.flush();
}
Results :
test0 : Runs: 241 iterations ,avarage milis = 246
test1 : Runs: 249 iterations ,avarage milis = 118
test2 : Runs: 269 iterations ,avarage milis = 5
test3 : Runs: 241 iterations ,avarage milis = 2
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;
public class Tester {
private static final String filePath = "c:\\bigFile.txt";
//private static final String filePath = "c:\\bigfileNewLine.txt";
private static final int numOfMethods = 4;
private static final int numOfIter = 1000;
public Tester() throws NoSuchMethodException {
System.out.println("Tester.Tester");
int[] milisArr = new int [numOfMethods];
int[] actualRun = new int [numOfMethods];
Random rnd = new Random(System.currentTimeMillis());
Long startMs = 0l, endMs = 0l;
Method[] method = new Method[numOfMethods];
for (int i = 0; i < numOfMethods; i++)
method[i] = this.getClass().getMethod("test" + i);
int testCount = 0;
while (testCount++ < numOfIter) {
int testMethod = rnd.nextInt(numOfMethods);
Method m = method[testMethod];
try {
System.gc();
startMs = System.currentTimeMillis();
String retval = (String) m.invoke(null);
endMs = System.currentTimeMillis();
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
milisArr[testMethod] += (endMs - startMs);
actualRun[testMethod]++;
System.out.println("Test name: " + m.getName() + " testCount=" + testCount + " Of " + numOfIter + " iteration, Total time :" + (endMs - startMs) / 1000.0 + " seconds");
}
System.out.println("Test Summery :");
for (int i = 0; i < numOfMethods; i++)
System.out.println("test" + i + " : Runs: " + actualRun[i] + " iterations ,avarage milis = " + milisArr[i]/numOfIter);
}
public static String test0() throws IOException {
InputStream file = getInputStream();
StringBuffer textBuffer = new StringBuffer();
int c;
while ((c = file.read()) != -1)
textBuffer.append((char) c);
file.close();
return textBuffer.toString();
}
public static String test1() throws IOException {
Reader reader = new FileReader(new File(filePath));
BufferedReader br = new BufferedReader(reader);
String line = br.readLine();
String result = line;
while (line != null) {
line = br.readLine();
if (line == null) {
} else {
result = result + "\n" + line;
}
}
br.close();
reader.close();
return result;
}
public static String test2() throws IOException {
byte[] buf = new byte[1024];
int l;
InputStream is = getInputStream();
StringBuffer tmpBuf = new StringBuffer();
while ((l = is.read(buf)) != -1) {
tmpBuf.append(new String(buf, 0, l));
}
is.close();
return tmpBuf.toString();
}
public static String test3() throws IOException {
File source = new File(filePath);
final DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(source)));
final byte[] buffer = new byte[(int) source.length()];
dis.readFully(buffer);
dis.close();
return new String(buffer, "UTF-8");
}
private static InputStream getInputStream() {
try {
return new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
try {
new Tester();
} catch (NoSuchMethodException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
This program is almost done. But the problem is when I edit and put it in a temp file, both the edited and unedited values are written. So, the temp file gets another value (which is the replacement). I would also like to know if there are ways on how I could rename the temp file. I tried looking at other questions' answers but none of those solved my problem.
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String edit = "";
String edit2 = "";
String data = "";
Scanner scanner = new Scanner(nfile2);
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String _bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
while(scanner.hasNext()){
boolean replace = false;
String str = scanner.nextLine();
if((str.contains(_btitle))&&(str.contains(_bauthor)))
{
String conv = str.toString();
System.out.println("Search found");
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
edit = str.replaceAll(_btitle, btitle1);
edit2 = str.replaceAll(_bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
replace = true;
//System.out.println("" +edit + "" +edit2); Test output
}
else {
//System.out.println("" +str); Test output
tbw1.append(str);
tbw1.append("\n");
tbw2.write(str);
tbw2.newLine();
}
}
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
EDIT 1:
Okay. Figured out how to delete and rename. Problem is I have to edit 2 times before it's finally deleted and renamed. (I removed the author because there are problems with the output).
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line = "";
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
while((line = br2.readLine()) !=null){
String btitle1;
if(line.contains(_btitle))
{
String conv = line.toString();
System.out.println("Search found");
btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
tbw1.append(line.replaceAll("" +_btitle, "" +btitle1));
tbw1.append("\n");
tbw2.write(line.replaceAll("" +_btitle, "" +btitle1));
tbw2.newLine();
}
else {
tbw1.append(line);
tbw1.append("\n");
tbw2.write(line);
tbw2.newLine();
}
}
twriter.flush();
twriter2.flush();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I am trying to design two different methods for a Java application. The first method will pass in a string of the name of a file, and return the text of a text file as a string. The second method will pass in the name of a file and the text, and create a new text file and output the string into the file.
Currently my code works without the methods, but I am trying to design it with a separation of concerns and low coupling. I am trying to modify it so I can just call a method to output any sort of data I have in a string to a text file.
Here is my code without the methods:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
//What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
//What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
//Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: " + outputFile);
// Variables to read and write the files
//Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
}
When creating a method for each of the "read" and "write" portions of my code, I constantly get errors that I assume are from the exception handling. Any thoughts on how to separate code that has exceptions involved?
Think in terms of single responsibility. You have two distinct operations that need to happen: reading and writing.
Let's start with reading. What you're doing right now to read the file surmises these lines:
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
Move that to a method.
private static String readFile(String inputFile) throws IOException {
BufferedReader input;
String total;
String line;// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
return total;
}
Here's what we did:
We have a variable total which is used elsewhere in the program, so that usage has to be preserved. We're returning String and will declare total = readFile(inputFile); on the outside.
We've changed nothing. This code will run the same way as it did without the method.
Now, if we want to move the writing functionality, which is:
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
...we just do.
private static void writeFile(String outputFile, String info) throws IOException {
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
}
Again, nothing's changed on this method. We don't have any other usages of any of the variables in here to worry about, so we can directly bring it across.
All said, that try block looks a bit anemic:
try {
total = readFile(inputFile);
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
writeFile(outputFile, info);
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
...which is a good thing.
I am not sure what are you asking about but try to create your own Exceptions and make your methods throw them like this
package com.qmic.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
// What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
// What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
// Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: "
+ outputFile);
// Variables to read and write the files
// Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
String readData = readFileContents(inputFile);
// Check to make sure we got the text files data
System.out.println("The total string says: \n" + readData);
// Call the reverseWords method to switch 'Hello' with 'World'
String reversedContents = reverseWords(readData);
writeToFile(outputFile, reversedContents);
} catch (ReadException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (WriteException ex) {
System.out.println("Error Writing file '" + outputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
public static void writeToFile(String fileName, String data)
throws WriteException {
BufferedWriter output = null;
try {
// Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + data);
File file = new File(fileName);
output = new BufferedWriter(new FileWriter(file));
output.write(data);
System.out.println("The output file: " + fileName
+ " has been written.");
}catch(IOException e){
throw new WriteException();
}finally{
try {
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String readFileContents(String fileName) throws ReadException {
// FileReader reads text files in the default encoding.
BufferedReader input = null;
String line = null;
String total = null;
try {
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
} catch (IOException e) {
throw new ReadException();
}finally{
//This is ugly code, if you are using java 7 you have extra option to better this
try {
input.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return total;
}
}
//make me public and move me to a separate file
class WriteException extends IOException {
}
//make me public and move me to a separate file
class ReadException extends IOException {
}
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.