failing to save data in a text file - java

I'm trying to make a class that takes info from the GUI this saves it to a text file which I use as my "Database" but for some reason the PrintWriter object doesn't write the new data in the file. here's my code
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class IO {
File f = new File("DB.txt");
PrintWriter write;
Scanner input;
String[][] data;
String nameToSearch;
// search constructor
public IO(String name) {
super();
nameToSearch = name;
try {
input = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found please restart the program");
}
data = new String[linesCounter()][2];
for (int i = 0; i < linesCounter(); i++) {
data[i][0] = input.nextLine();
data[i][1] = input.nextLine();
}
}
public IO(String name, String number) {
try {
write = new PrintWriter(new FileWriter(f, true));
} catch (IOException e) {
System.out.println("Error");
}
write.println(name);
write.println(number);
}
int linesCounter() {
try {
input = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found please restart the program");
}
int counter = 0;
while (input.hasNext()) {
input.nextLine();
counter++;
}
return counter / 2;
}
int contactFinder() {
for (int i = 0; i < linesCounter(); i++)
if (data[i][0].equalsIgnoreCase(nameToSearch))
return i;
return -1;
}
String nameGetter() {
return data[contactFinder()][0];
}
String numGetter() {
return data[contactFinder()][1];
}
}

you need to close the printwriter after you have finished writing into the file using printwriter.close()
try {
write = new PrintWriter(new FileWriter(f, true));
write.println(name);
write.println(number);
write.close();
} catch (IOException e) {
System.out.println("Error");
}
}
EDIT:
For your NoSuchElement Excepion, you should check if there is a nextline in the file before invoking Scanner.nextline() using Scanner.hasNextLine().
for (int i = 0; i < linesCounter(); i++) {
if(input.hasNextLine()){
data[i][0] = input.nextLine();
data[i][3] = input.nextLine();
}
}

It's possible the PrintWriter never got flushed. You can do this manually with
write.flush();
That will ensure the buffer gets written to the file.

Related

How to serialise and de-serialise an object in Java?

I need to modify class PrimeFactors so that it extends HashMap<Integer,ArrayList> and implements Serializable.
Let x be a number and y be an ArrayList containing the prime factors of x: add all <x,y> pairs to PrimeFactors and serialize the object into a new file.
Then write a method that de-serializes the PrimeFactors object from the file and displays the <x,y> pairs.
Right now, I am completely stuck and unsure how to continue. Any help would be greatly appreciated as I am very unfamiliar with this situation.
Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.ObjectOutputStream;
public class PrimeFactors2 extends HashMap<Integer,ArrayList<Integer>> implements Serializable {
public static void findFactor(int n) {
System.out.print("Factors for the number " + n + " is: ");
for (int i = n; i >= 1; i--) {
if (n % i == 0)
System.out.print(i + " ");
}
}
public static boolean checkForPrime(int number) {
boolean isItPrime = true;
if (number <= 1) {
isItPrime = false;
return isItPrime;
} else {
for (int i = 2; i <= number / 2; i++) {
if ((number % i) == 0) {
isItPrime = false;
break;
}
}
return isItPrime;
}
}
public static void main(String[] args) {
String path = "/Users/benharrington/Desktop/primeOrNot.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
ArrayList<Integer> list = new ArrayList<Integer>();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
int i = Integer.parseInt(str);
boolean isItPrime = checkForPrime(i);
if (isItPrime)
System.out.println(i + " is Prime");
else
System.out.println(i + " is not Prime");
if (isItPrime == false) {
list.add(i);
}
}
for (int k : list) {
System.out.println(" ");
findFactor(k);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What you did in your code is simply reading a file and parsing it.
If you want to serialize and se-derialize an object, it can be done with the following code:
PrimeFactors2 primeFactors2 = // you object creation code here;
// i.e:
// PrimeFactors2 primeFactors2 = new PrimeFactors2();
// primeFactors2.setX1(2);
// primeFactors2.setX2(3);
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/obj.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(primeFactors2);
out.close();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Then, in some context (same or another) in the same moment (or whenvever after you created the .ser object), you may de-serialize it with the following code:
try {
FileInputStream fileIn = new FileInputStream("/tmp/obj.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
PrimeFactors2 primeFactors2 = (PrimeFactors2) in.readObject();
// YAY!!! primeFactors2 is an object with the same values you created before
// i.e: primeFactors.getX1() is 2
// primeFactors.getX2() is 3
in.close();
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}

Why does .write not add the ints into the file? Java

I had a question regarding the File.io library. So in a class I had an assignment The Class Assignment
And I got stuck writing the part of the assignment where I need to add the ints into the output file. Here is my code right here,
import java.io.*;
import java.util.Scanner;
public class JH1_00668860 {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of prin
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
OutputStream ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + "asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileOutputStream(fileoutputname);
if (scan.hasNextInt() && scan.nextInt() >= 0) {
System.out.println(scan.nextInt() + "asfs");
ps.write(scan.nextInt());
} else {
System.out.println("You have ran out of data or you have a bad value");
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch(IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("file2.txt");
}
}
When I run it the console shows This
And then I go to the file on my computer named niceJob.txt which is starting as an empty file, Eclipse then says it is going to be changed, but then when i "reload" nothing shows up.
Can anyone help me debug this bug(or if it is some other thing that is happening?) Any help would be appreciated. Thanks
After your code ps.write(scan.nextInt()); try to put ps.write.flush(); or ps.flush();
EDIT:
If it still doesn't work add imports:
import java.io.BufferedWriter;
import java.io.FileWriter;
and change ps.write(scan.nextInt()); to
BufferedWriter writer = new BufferedWriter(new FileWriter(inputFilename));
writer.write(Integer.toString(scan.nextInt));
writer.newLine();
writer.flush();

Read/Write Data from Text To Excel and print NEXT,PREV,Current Line according to conditions [duplicate]

This question already has answers here:
Java Scanner to print previous and next lines
(2 answers)
Closed 6 years ago.
I have a text file from which according to some keywords I have to read that line and write that line into excel file. I did this, now I need to read next line and previous line and that lines also I need to write into excel sheet in different columns. How can I do this.
rahul1.txt
ABCD1 abhishek1 duplicatevalue jgf
ABCD2 abhishek2 duplicatevalue jgf
ABCD3 abhishek3 duplicatevalue jgf
ABCD4 abhishek4 duplicatevalue jgf
while (st1.hasMoreTokens()) {String txt = st1.nextToken();if (txt.contains("abhishek2")) {l1.add(txt);}
How can I print
ABCD1 abhishek1 duplicatevalue jgf prev Line
and
ABCD3 abhishek3 duplicatevalue jgf Next Line
in different column?
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;`
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ReadWrite {
int rownum = 1;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
boolean retu;
// BufferedReader reader = null;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("SampleSheet");
Row headerRow = firstSheet.createRow(0);
// headerRow.createCell(0).setCellValue("#");
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue(Message");
headerRow.createCell(2).setCellValue("name");
headerRow.createCell(3).setCellValue("address");
headerRow.createCell(4).setCellValue("contact");
headerRow.createCell(5).setCellValue("Next");
headerRow.createCell(6).setCellValue("Prev");
}
public static void main(String args[]) {
ReadWrite class2 = new ReadWrite();
class2.readfile();
}
void readfile() {
try {
FileInputStream fInput = new FileInputStream(
"D:\\Rahul\\rahul1.txt");
DataInputStream dis = new DataInputStream(fInput);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String lineStr;
String prevStr = "";
String nextStr = "";
//List<String> l1 = new ArrayList<String>();
int i;
int seqno = 1;
while ((lineStr = br.readLine()) != null) {
List<String> l1 = new ArrayList<String>();
if (lineStr.contains("Oracle")
|| lineStr.contains("SAP")
|| lineStr.contains("J2EE")) {
l1.add("C1");
l1.add(lineStr);
l1.add("M1");
l1.add("R1");
l1.add("V1");
l1.add(nextStr);
l1.add(prevStr);
} else {
prevStr = lineStr;
}
try {
if (l1 != null && l1.size() > 0)
retu = writenameinsheet(l1);
} catch (Exception e) {
e.printStackTrace();
}
seqno++;
i = 1;
}br.close();
FileOutputStream fos = null;
try {
File excelFile = new File("D:\\Rahul\\rahul.xls");
fos = new FileOutputStream(excelFile);
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
boolean writenameinsheet(List<String> l1) throws Exception {
try {
Row row = firstSheet.createRow(rownum);
for (int j = 0; j < l1.size(); j++){
Cell cell = row.createCell(j);
cell.setCellValue(l1.get(j));
}rownum++;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return true;
}
}

How to Access variable from another class in same package in java

I want to access the class Totalnoofwords in class newrepeatedcount.
I want to print "a" of class Totalnoofwords megring with
System.out.println("( "+file1.getName() +" )-" +"Total words counted:"+total);
in class newrepeatedcount.
So I could run both the code for getting System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);
Here is the snippet of 1 output which I wanted
( filenameBlog 39.txt )-Total no of words=83,total repeated words counted:4
Any suggestions Welcomed.
I am a beginner to java.
Here is my two class codes below.:)
Totalnoofwords.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import org.apache.commons.io.FileUtils;
public class Totalnoofwords
{
public static void main(String[] args)
{
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader (
new InputStreamReader(
new FileInputStream(file1)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "", str = "";
int a = 0;
int b = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
b++;
}
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
a++;
}
System.out.println(" Total no of words=" + a );
}
}
}
newrepeatedcount.java
package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount {
public static void main(String[] args){
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String st = null;
try {
st = IOUtils.toString(ins);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i1=0;i1<fr.length;i1++)
fr[i1]=-1;
//count words frequency
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
fr[i1]++;
}
}
}
//clean duplicates
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
if(i1!=j) words[i1]="";
}
}
}
//show the output
int total=0;
//System.out.println("Duplicate words:");
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
//System.out.println("Total words counted: "+total);
//System.out.println("Total no of repeated words : "+total+" ");
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total);
}
}}
I tried to put both the code into a single class
but neither one of the variable is working
System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);
When I run neither "a" or "total" is working.(vice versa) If i change the code (variable)order.
Anyone tell how should I get both the variable output??
:)
Here is my updated code.below.
package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount {
public static void main(String[] args){
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder\\");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = "", str = "";
String st = null;
try {
st = IOUtils.toString(ins);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i1=0;i1<fr.length;i1++)
fr[i1]=-1;
//count words frequency
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
fr[i1]++;
}
}
}
//clean duplicates
for(int i1=0;i1<words.length;i1++){
for(int j=0;j<words.length;j++){
if(words[i1].equals(words[j]))
{
if(i1!=j) words[i1]="";
}
}
}
int a = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
}
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st1 = new StringTokenizer(str);
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
a++;
}
int total=0;
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total+","+"total no of words:"+a);
// System.out.println("total no of words:"+a);
}
}}
package Packagename;
public class newrepeatedcount {
public static void main(String[] args){
Totalnoofwords B=new Totalnoofwords();
B.somename();
System.out.println("a:"+B.a);
}
}
The variables inside the main function cannot be accessed from other class.
So you can modify Totalnoofwords.java something like.
package Packagename;
public class Totalnoofwords
{
static int a = 1;
public void somename(){
Totalnoofwords A=new Totalnoofwords();
A.a+=5;
System.out.println("a"+A.a);
}
}
and your newrepeatedcount.java be like
package Packagename;
public class newrepeatedcount {
public static void main(String[] args){
Totalnoofwords B=new Totalnoofwords();
B.somename();
System.out.println("a:"+B.a);
}
}
It looks like you have 2 main methods in the same package, I'm not sure if you wanted it this way or not, but this won't work because your not overloading the methods. For instance currently you have public static void main(String[] args) in one class, If you change the other class to accept an extra argument public static void main(String[] args1, String[]args2).
Also in order to access your second class, as stated above you would use something like
Totalnoofwords totalNoofWords = new Totalnoofwords();
totalNoofWords.accessSomething();
But this won't work, because you don't have a constructor.

reading in a file from computer and editing it and saving as a new file

I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks

Categories

Resources