Having problems editing text files in java - java

Hey there somy code below is supposed to do one thing its hard to explain but i will try
for example this is the content of my txt file
atif12,123,0
kamran11,134,0
abh3,123,0
now if my username is kamran 11 and password is 134 which I entered so this program should turn the 0 to 500 and keep the rest as it is but my file gets updated and only shows this
kamran11,134,500
thus all is deleted and I don't know where I went wrong can someone correct me, please?
File file = new File("customer.txt");//this is the txtfile
ArrayList<String> lines = new ArrayList<>();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
lines.add(in.nextLine());
}
} catch (FileNotFoundException eo) {
throw new RuntimeException("File not found");
}
String comp=username+","+pass;
try (FileWriter out = new FileWriter(file)) {
for (int i = 0; i < lines.size(); i++) { //iterate over lines
String comp2=lines.get(i);
System.out.println(comp2);
if(comp2.contains(comp)){
String[] parts = lines.get(i).split(","); //split line by commas
for (int j = 0; j < parts.length; j++) { //iterate over parts
if (j == 2) { //if I hit the first element in this line that is a zero
int temp = Integer.parseInt(parts[j]);
temp = temp + 500;
parts[j] = Integer.toString(temp);
break; //break out of the loop
}
}
for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
System.out.println("this work");
out.write(parts[j]);
if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
out.write(',');
}
}
if (i < lines.size() - 1) { //add a line break if it isn't the last line
System.out.println("this work1");
out.write('\n');
}
//break;
}
else{
System.out.println("this dont work");
}
}
out.flush(); //write everything to the file
} catch (IOException ep) {
throw new RuntimeException("IO exception occurred");
}

Based on our discussion here, and the information provided in this question, I believe you want the following:
File file = new File("customer.txt");
ArrayList<String> lines = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String user = sc.nextLine(); //ask user for the username
String pwd = sc.nextLine(); //ask user for the password
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) { //read in all lines
lines.add(in.nextLine());
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
}
try (FileWriter out = new FileWriter(file)) {
for (int i = 0; i < lines.size(); i++) { //iterate over lines
String[] parts = lines.get(i).split(","); //split line by commas
if (parts[0].equals(user) && parts[1].equals(pwd)) { //if username and password match first and second parts of line, respectively
parts[2] = "500"; //set third part of line to 500
}
for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
out.write(parts[j]);
if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
out.write(',');
}
}
if (i < lines.size() - 1) { //add a line break if it isn't the last line
out.write('\n');
}
}
out.flush(); //write everything to the file
} catch (IOException e) {
throw new RuntimeException("IO exception occurred");
}

Related

reading and writing files java

I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}

I'm trying to print out this output of char from a string

public char[][] createGrid(String filename) throws IOException {
BufferedReader input;
String[]line;
char[][] newChar = new char [row] [cols];
try{
input =new BufferedReader(new FileReader(filename));
line =input.readLine().split(" ");
for(int i=0; i<line.length; i++){
if(line[0] == null){
System.out.println("no dimension was given");
} else {
for(int j =0; j<line.length; j++){
newChar[i][j]= line[j].charAt(i);
} //end of inner for loop
if(line[1]== null){
System.out.println("not enough columns ");
}// end of if
} // end of else
} //outer loop
I am trying to make my output exactly as it is in that image.
My image (format not supported to add it here)
I read a file, converts the file into a 2d array grid and prints it out.
If there is no proper formatting, it throws an exception as show in the image
You need to add an additional for statement with the parameters being the amount of rows so that you can read each of the lines in the table
try to use a while loop, you need to keep reading nextline until the line is empty.
public char[][] createGrid(String filename) throws IOException {
BufferedReader input;
String[]line;
char[][] newChar = new char [row] [cols];
try {
input = new BufferedReader(new FileReader(filename));
line = input.readLine();
while(line != null){
char[] lineArray =line.split(" ");
for (int i = 0; i < lineArray.length; i++) {
if (lineArray[0] == null) {
System.out.println("no dimension was given");
} else {
for (int j = 0; j < lineArray.length; j++) {
newChar[i][j] = line[j].charAt(i);
} //end of inner for loop
if (lineArray[1] == null) {
System.out.println("not enough columns ");
}// end of if
} // end of else
} //outer l
//read next line
line = input.readLine();;
}
```

Filling a matrix with content from file

I'm getting an error on my code. The goal is to add the contents of a file to a matrix.Then ill eventually need to parse it to add it to a graph so that i can eventually perform a depth-first search on it. But until then i need to figure this error out. I can't figure out what exactly is causing the error. so any help would be nice.
Here is the error im getting:
Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at DelivA.<init>(DelivA.java:53)
at Prog340.actionPerformed(Prog340.java:120
Here is the class i wrote.
public DelivA(File in, Graph gr) {
inputFile = in;
g = gr;
// Get output file name.
String inputFileName = inputFile.toString();
String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
String outputFileName = baseFileName.concat("_out.txt");
outputFile = new File(outputFileName);
if (outputFile.exists()) { // For retests
outputFile.delete();
}
try {
output = new PrintWriter(outputFile);
} catch (Exception x) {
System.err.format("Exception: %s%n", x);
System.exit(0);
}
// --------------------------------Deliverable
// A-------------------------------------------//
FileReader f1 = null;
int c = 0;
int r = 0;
try {
f1 = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanner = new Scanner(f1);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String splitLine[] = line.split(" ");
c = splitLine.length;
r++;
}
String[][] matrix = new String[c][r];
#SuppressWarnings("resource")
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
String words = s1.next(); // will scan each row of the file
for (int col = 0; col < matrix[row].length; col++) {
char ch = words.charAt(col); // will put each character into array
matrix[row][col] = String.valueOf(ch);
}
}
}
}
Your problem is probably here:
String words = s1.next():
You are not verifying if there is any line available.
You should do something like this:
...
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
if (scanner.hasNextLine()){
String words = s1.next(); // will scan each row of the file
...
Of course you should rethink the code logic accordingly...

Removing last line and white spaces while writing arrays to file

Writing data in a file with loop line by line will cause the last line to be 'newline'. Consider this:
try {
outFile = new BufferedWriter(new FileWriter(outFileName));
for (int i = 0; i < some_condition; i++) {
for (String record: aLine) {
outFile.write(record + " ");
}
outFile.write("\n");
}
} catch(IOException e) {
System.out.println("found error!");
}
Also the last item in each row is " ". What is the efficient way to trim such white spaces and newline?
I can divide the loop to 0...n-2 and n-1 but is not very good for big codes. I am looking for some file based solutions like this:
try {
outFile = new BufferedWriter(new FileWriter(outFileName));
for (int i = 0; i < some_condition; i++) {
for (String record: aLine) {
outFile.write(record + " ");
}
outFile.REMOVE_LAST_CHARACTER; // trim " "
outFile.write("\n");
}
} catch(IOException e) {
System.out.println("found error!");
}
outFile.REMOVE_LAST_LINE;
Is that possible?
Append it to StringBuilder and then at last remove the last character by trimming the String or you can manually check in for loop while appending " ". For \n newline character, You can append every line to a main StringBuilder which keeps track of whole file and trim the extra space at last.
StringBuilder all_lines = new StringBuilder(); //To store every line
for (int i = 0; i < some_condition; i++) {
StringBuilder line = new StringBuilder();
for (String record: aLine) {
line.append(record).append(" "); //To store every words
}
all_lines.append(line.toString().trim());
all_lines.append("\n");
}
outFile.write(all_lines.toString().trim());
outFile.close();
You can write the space and new line before the record, here is an example:
try {
outFile = new BufferedWriter(new FileWriter(outFileName));
for (int i = 0; i < some_condition; i++) {
if(i!=0){
outFile.write("\n");
}
boolean firstRecord = true;
for (String record: aLine) {
outFile.write((firstRecord ? "" : " ") + record);
firstRecord = false;
}
}
} catch(IOException e) {
System.out.println("found error!");
}

How to count number occurrences of a word in a file using BufferedReader in Java

the task is to find number of occurrences of a particular word in a file
that person wrote herself.
public void reader() {
BufferedReader myR = myReader("enter the name of a file: ");
int count = 0;
String substring = readLine("enter the string to count for entry: ");
try {
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
myR.close();
} catch (IOException e) {
throw new ErrorException(e);
}
println("number of words is: " + count);
}
private BufferedReader myReader(String prompt) {
BufferedReader rd = null;
while (rd == null) {
try {
String name = readLine(prompt);
rd = new BufferedReader(new FileReader(name));
} catch (FileNotFoundException e) {
println("wrong file entered");
// e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return rd;
}
So the problem is that i can't figure out what to do if in my text file number of word i was checking is 4, but the code prints 671
the problem lies in this loop:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
now suppose your bufferedReader reads a line "hie i am user".
the size of this string is 13 so string.length(); would return 13.
that means you would be checking the same line for 13 iterations for your match.
So, suppose if you are looking for a match say "user" then checking for "user" on the same line for 13 times would make your count go up to 13.
you can replace the above code with this code:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
String[] slist = s.split(" ");
for(int j=0; j<slist.length(); j++){
if(slist[j].contains(substring)){
count++;
}
}
}
ohh!! you should have mentioned that you wanna do it without using an array.
this snippet should help you:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.equals(" ")){
String temp = s.substring(j+1, s.length());
String word = temp.substring(0,temp.indexOf(" ")-1);
if(temp.equalsIgnoringCases(word)){
count++;
}
}
}
}
now what i am doing here is first of all i am looking for a space in the whole string and upon finding one, I am extracting a substring starting from the index next to the index of space to the end of the string.
Now from this extracted substring, I am further extracting a substring from index zero up till the first space. this string is essentially a word suitable for comparison.

Categories