How to use JFrame to output file content in system console output? - java

I am using JFrame Java Swing for a piece of code shown below:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String filename = (jTextField1.getText());
if (filename.endsWith(".log")) {
Scanner inFile1 = new Scanner(filename).useDelimiter(";");
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
String token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
This code works but it only displays the file name as the file name itself (e.g. If my file name = lalala.txt, the output in console would be lalala.txt) I have tried this code but it does not display the contents inside the file. How do I go about displaying the contents in the file while using JFrame as my GUI in my console output? My GUI consist of a text field which will display the file name and when I click the jButton2, I want the button to show the the content of the file instead of the file name by itself. It runs perfectly fine but it is not what I want for my output.

You are using:
new Scanner(filename).useDelimiter(";");
Which in turn is reading the data from the string filename. Instead use:
new Scanner(new File(filename)).useDelimiter(";");

Simply use:
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("absolute path to your text file...")),"UTF8"));
String buf;
while ((buf = in.readLine()) != null)
{
System.out.println(buf);
}
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

Related

check if the word in the set equals word in outside file

I have a set of words and an outside file.
I want to check if a word in the set is already present in the outside file. If the word is already in the file, then do nothing, if the word is not in the outside file already, then add it to the outside file.
This is the code I have written:
public static void toFile(Set<String> vocab, String filename)
{
try
{
for(String vocabWord : vocab)
{
File file = new File(filename);
Scanner sc2 = new Scanner(file);
while(sc2.hasNextLine())
{
String docWord = sc2.nextLine();
if (!(vocabWord.equals(docWord)))
{
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
else
break;
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
I am using three different text documents to test it, have the line "test file one", "test file two", and "test file three".
The output I was expecting was: "test file three" (it is connected with a stop list which one and two are part of, and has been working)
However, when I run it, either with only one of the files or all three consecutively, the file always comes out empty.
I tried changing up things in the method, but nothing has worked, I either get an infinite loop or nothing in the outside file.
I am not sure what I am missing... I would really appreciate any help.
I tried this and added some comments for explanation. I have tested on local machine and it works
public static void toFile(Set<String> vocab, String filename) {
try {
for(String vocabWord : vocab) {
//task for each String in our Set
File file = new File(filename);
Scanner sc2 = new Scanner(file);
boolean exists = false;//lets say it doesn't exist
while(sc2.hasNextLine()) {
//task for each line in the text
//search the whole file first for the word
String docWord = sc2.nextLine();
if (docWord.equals(vocabWord)){
exists = true;
break;
}
}
if (!exists) {
//add the vocabWord only if it doesnt exists
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
To append the missing vocabulary in order of vocab, you can reduce the file operations
as such:
public static void toFile(Set<String> vocab, String filename) {
try {
Charset charset = Charset.defaultCharset();
Path path = Paths.get(filename);
Set<String> existing = Files.lines(path, charset)
.collect(Collectors.toSet());
if (!existing.isEmpty()) {
try (BufferedWriter bw = Files.newBufferedWriter(path, charset,
StandardOpenOption.APPEND);
PrintWriter printWriter = new PrintWriter(bw)) {
vocab.stream()
.filter(word -> !existing.contains(word))
.forEach(word -> printWriter.println(word));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

How to get scanner to read pipe delimited txt file in java

I've been trying to get a scanner to read and sort a pipe delimited text file using delimiter \|but i cant seem to get it to sort or display the reformatted file. When I open the filechooser it also throws and error when i try to import the scanner. The data in the txt file will be a mixture of strings and ints
Scanner scanner = new Scanner("/n");
scanner.useDelimiter(Pattern.compile("[|\n]"));
JTable JT = new Jtable();
List<Integer> List = new ArrayList<>();
System.out.println(scanner.nextInt());
System.out.println(scanner.nextInt());
File readFile; //creates file variable
JFileChooser jFileChooser_Open = new JFileChooser();
int option = jFileChooser_Open.showOpenDialog(this);
readFile = jFileChooser_Open.getSelectedFile();//instantiates file and
gets selected file from jfilechooser
String line;
try (FileReader inStream = new FileReader(readFile); BufferedReader
inBuffer = new BufferedReader(inStream)) {
//create variable line
while ((line = inBuffer.readLine()) != -1 ) {
while (scanner.hasNext()) {
List.add(line);
List.add(scanner.nextInt());
}
System.out.println(List);
}
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE,null, ex);
}
Also I want to get the newly formatted string to be displayed in my table or a text area. But if you guys could help me get it to print to the console, then I would greatly appreciate it.

console output on gui

I have problem with console output. I did search for one day now and i still can't fix the problem. I have tried adding text on JTextArea manually and it works, so gui should be fine. IF i change code to System.out.println(s), it will writte in console successfully. Here is my code:
public static void runSystemCommand(String command) {
String message=null;
int i=0;
while (i<1){
try {
gui area=new gui();
// ArrayList<String> sList = new ArrayList<String>();
areaField=new JTextArea();
sarray = new String [500];
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
area.jTextArea.append(s+ "\n"); //this doesnt work..
}
Thread.sleep(9000);
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
In your code you have an empty string String s = ""; try to assign some string to s like this:
String s = "some value";
area.jTextArea.append(s+ "\n");
You are appending to the wrong JTextArea.
In your pingmain class you create a new instance of gui which is never shown to the user. In this invisible instance you correctly add the text to the textarea.
If you instead add a gui area parameter to your runSystemCommand method and give this as second arguemnt to the method call in gui, you will see your output in your textarea.

How to read in a text file (line-by-line) and use the output as nameS to create .pdf Files in java?

I'm writing a program that would allow me to create several PDF Files with a set of given names (from a text file, each name represented by a line in the file). These PDF Files will have a watermark on each page.
Here's the code I'm using:
public class watermark {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\Documents\\java\\listcos.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
try {
String a = line;
PdfReader Read_PDF_To_Watermark = new PdfReader("Sample.pdf");
int number_of_pages = Read_PDF_To_Watermark.getNumberOfPages();
PdfStamper stamp = new PdfStamper(Read_PDF_To_Watermark, new FileOutputStream("New_" + line + ".pdf"));
int i = 0;
Image watermark_image = Image.getInstance("watermark.jpg");
watermark_image.setAbsolutePosition(20, 40);
PdfContentByte add_watermark;
while (i < number_of_pages) {
i++;
add_watermark = stamp.getUnderContent(i);
add_watermark.addImage(watermark_image);
}
stamp.close();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}catch (IOException e) {
e.printStackTrace();}
}
}
I was able to produce a .pdf file but the name I got was "New_null.pdf". Plus, I can only generate one .pdf files. I'd like to know how to generate as many .pdf files as the number of names in the given text file.
Any idea would be greatly appreciated.
Thanks a lot in advance.
Zestos.
Create the pdf inside the while loop which gets the lines. Right now, line is null because you reached End of File. Move everything in the loop!.

MAP Problem with JAVA and Sqlite database

I have another question for you:
The code below does the following
For each file in a folder
Open the file and read its contents
Take and divide each line into tokens
Save each token (word) in a hasMap
Prepare a database query (Select form words ...)
For each match found between the tokens and the words contained in the database Write 1.0, if true, otherwise 0.0;
The problem arises at this point:
try{
while (rs_mail.next()) {
if(result_m.contains(rs_mail.getString("voc_w").toString())) //HERE I GET THE ERROR! java.lang.NullPointerException
out_final.print("1.0;");
else
out_final.print("0.0;");
}//Close While
} //Close TRY
finally{
rs_mail.close();
//result_m.clear();
mail.clear(); //Clear MAP
}
Below the complete code:
String path ="C:/Users/.../file";
File currentDIR = new File("C:/Users/.../file");
File files_mail[]=currentDIR.listFiles();
String tmp_mail="";
// prepares the file tmpTraning.txt to receive value 1.0, 0.0 obtained by comparison with database
PrintWriter out_final=null;
File ff=new File("C:/Users/.../tmpTraning.txt");
//Seach for File in DIR
for( File fX : files_mail ){
String name_Filex = fX.getName();
FileReader fr = null;
BufferedReader fINx = null;
String sx;
//Create MAP
Map<String, Set<String>> mail = new HashMap<String, Set<String>>();
//Open File
try{
Set<String> sq = new HashSet<String>();
fr = new FileReader(path+"/"+name_Filex);
fINx = new BufferedReader(fr);
sx = fINx.readLine();
//scroll the file
while(sx != null) {
StringTokenizer stq = new StringTokenizer(sx);
while(stq.hasMoreTokens()) { //Extract form line the single word
tmp_mail = stq.nextToken();
sq.add(tmp_mail.toString().toLowerCase()); //add the word to sq -> HashMap
mail.put(nome_Filex, sq);
}// Close st.hasMoreTokens()
sx = fINx.readLine();
} //Close while for scroll File
fr.close(); //Close fileReader
sq.clear(); //Clear HasSet
} //Close il TRAY
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Set<String> result_m = mail.get(name_Filex);
ResultSet rs_mail = stmt.executeQuery("SELECT DISTINCT voc.words as voc_w FROM voc_words as voc");
//Prepare for writing on the file " tmpTraning.txt "
OutputStreamWriter fout_f = new OutputStreamWriter(new FileOutputStream(ff,true));
out_final = new PrintWriter(fout_f);
try{
while (rs_mail.next()) {
//If the word extract from the database is in MAP (name_Filex) then print 1.0; on the file tmpTraning.txt
if(result_m.contains(rs_mail.getString("voc_w").toString())) //HERE I GET THE ERROR! java.lang.NullPointerException
out_final.print("1.0;");
else
//else print 0.0;
out_final.print("0.0;");
}
} //Close TRY
finally{
rs_mail.close();
//result_m.clear();
mail.clear(); //Clear MAP
}
out_final.println(""); //Send CR char ASCII to set the coursor for the next file on the new line
out_final.close();
out_final.flush();
} // End SCAN DIR
Thanks for any advice!
Code changes - print the contents of result_m:
String path ="...";
File currentDIR = new File("...");
File files_mail[]=currentDIR.listFiles();
String tmp_mail="";
// prepares the file tmpTraning.txt to receive value 1.0, 0.0 obtained by comparison with database
PrintWriter out_final=null;
File ff=new File("...");
//Seach for File in DIR
for( File fX : currentDIR.listFiles() ){
String name_Filex = fX.getName();
String sx;
//Create MAP
Map<String, Set<String>> mail = new HashMap<String, Set<String>>();
//Open File
try{
Set<String> sq = new HashSet<String>();
BufferedReader fINx = new BufferedReader(new FileReader(fX));
sx = fINx.readLine();
//scroll the file
while(sx != null) {
StringTokenizer stq = new StringTokenizer(sx);
while(stq.hasMoreTokens()) { //Extract form line the single word
tmp_mail = stq.nextToken();
sq.add(tmp_mail.toString().toLowerCase()); //add the word to sq -> HashMap
mail.put(name_Filex, sq);
}// Close st.hasMoreTokens()
sx = fINx.readLine();
} //Close while for scroll File
fr.close(); //Close fileReader
sq.clear(); //Clear HasSet
} //Close il TRAY
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
/*
* print the contents of result_m
*/
System.out.println("----- START FILE -----");
Set<String> result_m = mail.get(name_Filex);
Object[] toArray_m = mail.get(name_Filex).toArray();
for (int ncc=0; ncc<result_m.size();ncc++){
System.out.println(toArray_m[ncc]);
}
System.out.println("----- END FILE -----");
} // End SCAN DIR
if the file read by the program contains blank lines (no char, no string), it saves a null value
Is there a good reason that you are calling toString() on a string? If getString("voc_w") is null, then it will cause your exception.
As manji pointed out in the comment, it's either the call I mentioned, or the result_m Set that are null.
There are a great many issues with your code, unfortunately. Here's one that springs to my eye immediately.
You are using string manipulation to create the filename that you are passing in to the FileReader constructor, despite the fact that as far as I can see the file being opened is one returned from a listing of the directory. That's just asking for trouble. Instead, the code would be better off written more like this...
// Lots of things are omitted; this is just a sketch...
String path = "...";
File currentDIR = new File(path);
for (File fX : currentDIR.listFiles()) {
try {
BufferedReader fINx = new BufferedReader(new FileReader(fX));
// ...
} catch (IOException e) {
e.printErrorStack();
}
}
However, you have more problems than that. For example, the use of sq.clear() has bad code smell. You've just stowed a reference to that Set in the Map; why are you deleting its contents again? The variable is falling out of scope; you can simply leave that code out. The down-stream consequences of that clear() are that result_m later on will be an empty set, so its contains test will always return false. I can't tell offhand whether that's the cause of your rogue null, but it's got to be wrong on the basis of what you're claiming to want to do.
Try refactoring that code into several smaller pieces that are easier to verify correct. I suggest as a first cut: a private method to get the Set of words from a File (supplied as argument), a private method to compare a Set of words against the database, and a method that combines those two with some looping to achieve your overall goal.

Categories

Resources