JAVA Replacing line or strings in textfile not working - java

So i have made two methods that creates the file (createFile(); and one to fill the textfile with empty highscores if none are set.
public class HighscoreList {
static String highscore = null;
static PuzzleModel theModel;
static File file = null;
public static int nom;
public static int tu;
public static int nor;
public static String search = " ";
static String replace = "2";
static String numberOfRows = null;
static String timeUsed = " ";
static String numberOfMoves = " ";
public static void main(String[] args) {
createFile();
isEmptySetEmptyHighscore();
// checkScore(0);
getHighscore(0);
}
public static void createFile() {
file = new File("C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt");
System.out.println("Created file " + file.getName());
if (!file.exists()) {
System.out.println("File didn't exist creating new file");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void isEmptySetEmptyHighscore() {
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if (br.readLine() == null) {
setEmptyHighscoreFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setEmptyHighscoreFile() {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("File is empty, fills with empty fields");
for (int i = 3; i < 101; i++) {
bw.write(i + ":" + numberOfMoves + ":" + timeUsed+"\n");
}
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
I have a getHighscore() that reads the two empty " " fields with moves and timeUsed. It is currently able to read this, but i cant write to those empty spaces in the textfile and replace them with actual numbers that i want.
EDIT: With the replace command it just adds it to the bottom of the file.
Is there something wrong with my code that re erases the text that i try to replace or how do i do it?
I tried something like this:
public static void writeToFile(int rows) {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if(br.readLine().split(":")[0].equals(Integer.toString(rows+1))){
bw.write(br.readLine().replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

have you try this ?
String line = br.readLine();
if(line.split(":")[0].equals(Integer.toString(rows+1))){
bw.write(line.replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}

Related

Print To File in Java

i have a problem in my java exercise.
i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file..
i tried to debug that but i cant find any mistake
i will put the code of my classes here:
This is Demo Class which i run the code from
public class Demo {
public static void main(String[] args) {
System.out.println("Insert number of Contacts:");
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
Contact[] contacts = new Contact[val];
for(int i = 0 ; i < val; i++) {
System.out.println("Contact #"+(i+1));
System.out.print("Owner: \n");
String owner = scanner.next();
System.out.print("Phone number: \n");
String phoneNum = scanner.next();
System.out.print("Please Select Group:\n"
+ "1 For FRIENDS,\n" +
"2 For FAMILY,\n" +
"3 For WORK,\n" +
"4 For OTHERS");
int enumNum = scanner.nextInt();
Group group;
switch(enumNum) {
case 1:
group=Group.FRIENDS;
break;
case 2:
group=Group.FAMILY;
break;
case 3:
group=Group.WORK;
break;
default:
group=Group.OTHERS;
}//switch end
contacts[i] = new Contact(owner,phoneNum,group);
}//loop end
System.out.println("Insert File name");
String fileName = scanner.next();
File f=null;
for(int i = 0 ; i < val; i++) {
if(i==0) {
f = new File(fileName);
contacts[0].Save(fileName);
}
else {
contacts[i].Save(f);
}
}
}
}
This is Contact Class:
enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS
};
public class Contact {
private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;
public Contact(String owner ,String phoneNumber,Group group) {
setPhoneNumber(phoneNumber);
setOwner(owner);
setGroup(group);
}
public Contact(String fileName) {
File file = new File(fileName+".txt");
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public Contact(File file) {
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
if(f.createNewFile()) {
System.out.println("File created");
pw = new PrintWriter(f); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
public void Save(File f) {
PrintWriter pw=null;
try {
pw = new PrintWriter(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.println(phoneNumber+"\n"+owner+"\n"+group);
pw.close();
}
public String toString() {
return phoneNumber+"\n"+owner+"\n"+group;
}
}
Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.
Firstly, let's create a new save method with such signature:
public void save(PrintWriter writer)
I have also used the lowercase name of the method due to Java naming convention.
Now the implementation of save method will look like this:
writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");
Then we should replace the usage of Save method with the new one. Here is your code:
String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
if(i == 0) {
f = new File(fileName);
contacts[0].Save(fileName);
} else {
contacts[i].Save(f);
}
}
In order to fix the issue we can change it like this:
String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < val; i++) {
contacts[i].save(writer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have also used try-with-resources which closes the PrintWriter automatically.
From the Javadoc of the constructor of PrintWriter:
public PrintWriter​(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.
Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
//System.out.println("File created"); You don't need to create new file.
FileWriter fw=new FileWriter(f,true):// second argument enables append mode
pw = new PrintWriter(fw); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}

String[] cannot be converted to State[]

Just wondering what I have done wrong here I'm getting an error in the method setLine() which is:
error: incompatible types: String[] cannot be converted to State[]
Im not too sure on what to do to fix it since I need the line to be split and stored in that state array so I can determine whether if it is a state or location when reading from a csv file.
public static void readFile(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int stateCount = 0, locationCount = 0;
String line;
try
{
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
if (line.startsWith("STATE"))
{
stateCount++;
}
else if (line.startsWith("LOCATION"))
{
locationCount++;
}
line = bufRdr.readLine();
}
fileStrm.close();
State[] state = new State[stateCount];
Location[] location = new Location[locationCount];
}
catch (IOException e)
{
if (fileStrm != null)
{
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
public static void processLine(String csvRow)
{
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ":");
while (strTok.hasMoreTokens())
{
thisToken = strTok.nextToken();
System.out.print(thisToken + " ");
}
System.out.println("");
}
public static void setLine(State[] state, Location[] location, int stateCount, int locationCount, String line)
{
int i;
state = new State[stateCount];
state = line.split("="); <--- ERROR
for( i = 0; i < stateCount; i++)
{
}
}
public static void writeOneRow(String inFilename)
{
FileOutputStream fileStrm = null;
PrintWriter pw;
try
{
fileStrm = new FileOutputStream(inFilename);
pw = new PrintWriter(fileStrm);
pw.println();
pw.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch (IOException ex2)
{}
}
System.out.println("Error in writing to file: " + e.getMessage());
}
}
This error occurs, as it just says 'String[] cannot be converted to State[]'. That is like you wanted to store an Integer into a String, it's the same, because the types don't have a relation to each other (parent -> child).
So if you want to solve your problem you need a method which converts the String[] into a State[]. Something like this:
private State[] toStateArray(String[] strings){
final State[] states = new State[strings.length];
for(int i = strings.length-1; i >= 0; i--){
states[i] = new State(strings[i]); // here you have to decide how to convert String to State
}
return states;
}

Storing Text file or folder in a header file and retrieve the data

How to Store Value stored in a folder/Text file in a header file and import it again to the program without the use of external memory or drives
This code gives me a incremented value each time when I run it and stores the value in a file. But I need to store the text file in the header itself rather than drives/external storage. So do we have any storage headers that I can use it instead of drives
class Test {
public static void main(String[] args) {
Test test1 = new Test();
test1.doMethod();
}
public int getCount() {
int count = 0;
try {
if (!new File("d:\\myCount.txt").exists())
return 1;
else {
BufferedReader br = new BufferedReader(new FileReader(new File("d:\\myCount.txt")));
String s = br.readLine();
count = Integer.parseInt(s);
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
public void putCount(int count) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("d:\\myCount.txt")));
bw.write(Integer.toString(count));
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doMethod() //Put Method//
{
int count = getCount();
if (count < 10000) {
NumberFormat nf = new DecimalFormat("0000");
System.out.println(" ID:" + nf.format(count));
count++;
putCount(count);
} else if (count >= 10000)
System.out.print("NO VACCANCY");
}
}

Why is the value not printing in the text view?

I'm trying to print '1' or '0' in text view if it passes the if statements. I ran it in the debug mode, and it all works, but it is not printing in the text view. How do I fix this I tried a lot of stuff, but I'm still stuck.
public class Readcsv {
private static final String FILE_DIR = "/Users/Me/Downloads";
private static final String FILE_TEXT_NAME = ".csv";
public static void main(String [] args) throws Exception{
PrintWriter writer = new PrintWriter("/users/Me/Documents/Test.txt", "UTF-8");
int i=-1;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
//Find Number of Files
String[] list = new Readcsv().FileCount(FILE_DIR, FILE_TEXT_NAME);
System.out.println("Total Files = " + list.length);
while(i++ < list.length){
System.out.println("Loop Count = " + i);
try {
br = new BufferedReader(new FileReader("/users/Tanuj/Downloads/" + list[i]));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] strRecord = line.split(cvsSplitBy);
if (!strRecord[0].equals("timestampMs")){
int c = Integer.parseInt(strRecord[4]);
int e = Integer.parseInt(strRecord[5]);
if(c>e){
writer.print("1");
}
else{
writer.print("0");
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} //End of while
writer.close();
} //End of Main
public String[] FileCount(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
if(dir.isDirectory()==false){
System.out.println("Directory does not exists : " + FILE_DIR);
return null;
}
// list out all the file name and filter by the extension
String[] list = dir.list((FilenameFilter) filter);
return list;
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
have you tryed BufferedWriter?
File file = new File("Test.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("something");
bw.newLine();
bw.close();

read and write text and changing at only one column

my text
is like that
SEHiR;iL;iLCE;Tip;22356
S SI n;ISTA;ANK;A:S;22356
K K n;IS:TA;BB;B:S;22356
A A b;IS.TA;CC;DK;22356
G S b;ISTA;DD;O:P;22356
I want to change TIP column. I want to put "." instead of ":" for only Tıp column which include A:S,B:S etc.. And I want to write line before changing and after changing to csv. How can I do that? I write something but it has problem at
if(eD.tip.contains(":")) part because it dont continue to hS.Add(eD)
endeks.put("", hS); ı don’t want use “” string.
I do not have to use HasMap I could not write output what I want..
ı expected this output
S SI n;ISTA;ANK;A:S;22356
S SI n;ISTA;ANK;A.S;22356
K K n;IS:TA;BB;B:S;22356
K K n;IS:TA;BB;B.S;22356
G S b;ISTA;DD;O:P;22356
G S b;ISTA;DD;O.P;22356
public class MaliyeVknmDegil {
static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
static HashMap<String,HashSet<EndeksDegeri>> endeks = new HashMap<String, HashSet<EndeksDegeri>>();
static PrintWriter pW;
static EndeksDegeri eD = new EndeksDegeri();
static String satır;
private static PrintWriter pW2;
public static void main(String[] args) {
FileInputStream fIS;
FileOutputStream fOS;
try {
fIS = new FileInputStream("C:\\deneme\\DENEME.csv");
Reader r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
fOS = new FileOutputStream("c:\\yazdirilan\\deneme.csv");
Writer w = new OutputStreamWriter(fOS, "UTF-8");
pW2 = (new PrintWriter(w));
String satır;
String[] eleman;
while ((satır = bR.readLine()) != null) {
eleman = satır.split(";");
if(satır.contains(":")){
pW2.write(satır);
}
HashSet<EndeksDegeri> hS = new HashSet<EndeksDegeri>();
for (int i = 0; i < eleman.length; i++) {
// alteleman=eleman[i].split(" ");
EndeksDegeri eD = new EndeksDegeri();
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
if(eD.tip.contains(":")){
eD.tip.replaceAll(":", ".");
eD.tip = eleman[3];
}
eD.numara = Integer.parseInt(eleman[4]);
hS.add(eD);
}
endeks.put("", hS);
}
bR.close();
// yazdir
HashSet<EndeksDegeri> hS;
for (String s : endeks.keySet()) {
hS = endeks.get(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}// main end
}// clas end
package stackoverflow;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
public class TipChange {
private static String inputPath = "input.csv";
private static String outputPath = "output.csv";
private static BufferedReader bufferedReader;
private static PrintWriter printWriter;
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream(inputPath);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(reader);
FileOutputStream outputStream = new FileOutputStream(outputPath);
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
printWriter = new PrintWriter(writer);
String line;
while ((line = bufferedReader.readLine()) != null) {
EndeksDegeri eD = lineToClass(line);
if (shouldOutput(eD)) {
printWriter.append(classToLine(eD, true));
printWriter.append(classToLine(eD, false));
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean shouldOutput(EndeksDegeri eD) {
if (!eD.tip.contains(":")) {
return false;
}
return true;
}
private static String classToLine(EndeksDegeri eD, boolean original) {
if (!original) {
eD.tip = eD.tip.replace(":", ".");
}
return eD.sirket.concat(";")
.concat(eD.sehir).concat(";")
.concat(eD.ilce).concat(";")
.concat(eD.tip).concat(";")
.concat(String.valueOf(eD.numara)
.concat("\r\n"));
}
private static EndeksDegeri lineToClass(String line) {
String[] element = line.split(";");
EndeksDegeri endeksDegeri = new EndeksDegeri();
endeksDegeri.sirket = element[0];
endeksDegeri.sehir = element[1];
endeksDegeri.ilce = element[2];
endeksDegeri.tip = element[3];
endeksDegeri.numara = Integer.valueOf(element[4]);
return endeksDegeri;
}
private static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
}
Sample input:
SSI;ISTA;ANK;A:S;22356
KK;IS:TA;BB;B:S;22356
AA;IS.TA;CC;DK;22356
GS;ISTA;DD;O:P;22356
Generated Output:
SSI;ISTA;ANK;A:S;22356
SSI;ISTA;ANK;A.S;22356
KK;IS:TA;BB;B:S;22356
KK;IS:TA;BB;B.S;22356
GS;ISTA;DD;O:P;22356
GS;ISTA;DD;O.P;22356
Your code will produce a NullPointerException in the line: if(eD.tip.contains(":")){
That is because when a new EndeksDegeri instance is created all its fields are null you cannot call contains() on a null string.
Check the example code below (It writes to the console but it should get you going)
static class EndeksDegeri {
String sirket;
String sehir;
String ilce;
String tip;
int numara;
// I have added this method for convenience to write to the output
public String toString() {
return sirket + ":" + sehir + ":" + ilce + ":" + tip + ":" + numara;
}
}
while ((satir = bR.readLine()) != null) {
eleman = satir.split(";");
boolean found = false;
EndeksDegeri eD = new EndeksDegeri();
// first set all fields to not get exception
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
eD.tip = eleman[3];
eD.numara = Integer.parseInt(eleman[4]);
// check if the line contains ":"
if (eD.tip.contains(":")) {
// If yes, write the original line first
System.out.println(eD.toString());
// Change the record
eD.tip = eD.tip.replaceAll(":", ".");
found = true;
}
if (found) {
// write the corrected line now
System.out.println(eD.toString());
}
}
// Will print only the lines with ":" and its correct version
SSI:ISTA:ANK:A:S:22356
SSI:ISTA:ANK:A.S:22356
KK:IS:TA:BB:B:S:22356
KK:IS:TA:BB:B.S:22356
GS:ISTA:DD:O:P:22356
GS:ISTA:DD:O.P:22356

Categories

Resources