Overwriting a line in java txt file - java

So I have created this method which at the end displays the whole line because i am displaying the array after converting and editing it. So my Question is how can i know overwrite the array to the same line i grabbed it from. thanks in advance and here is my code.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
i am using string accountNumber to grab the specific line that i need. after getting the line i am changing it to an array while splitting the index with str.split(" "); . After that i know that i need to edit index number [3]. so i do so and then i put it back into the array. the final thing i need to do is to right the array back now.

You can keep track of the input from the file you are reading and write it back with the modified version.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}

This is how i understand the question that you have a file you will read it line by line and will make some changes and want to write it again at the same position. Create a new temp file and write the contents to the temp file, if changed write the changed result if not write it as it is.
And at last rename the temp to your original file name

Related

Copying a text file into a 2D char array in java

I'm working on reading a text file that contains an 5x6 character big ascii image. Here's what i've done so far:
...
Scanner fileReader = null;
try{
File file = new File(fileName);
fileReader = new Scanner(file);
int offset = 0;
char [][] pic = new char[5][6];
while (fileReader.hasNextLine()){
for (int u = 0; u < row; u++){
for (int i = 0; i < col; i++){
String line = fileReader.nextLine();
pic[u][i] = line.charAt(offset++);
}
}
return pic;
}
fileReader.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}...
This gives me a "no line found" message. I'm wondering if the scanner i use to ask the user the name of the file is a part of the problem. Here's what that looks like:
System.out.println("Hello! I load files.");
System.out.println("Please, enter file name:");
Scanner reader = new Scanner(System.in);
String fileName = reader.nextLine();
I've tried to close the reader after but it didn't change anything. Any help is much appreciated.
Several things :
First, you are attempting to read a line for each index of your array (that is row*col times).
Second, you should only read a line by row.
You may replace your whole while loop with this :
for (int u = 0; u < row && fileReader.hasNextLine(); u++) {
String line = fileReader.nextLine();
for (int i = 0; i < col; i++) {
pic[u][i] = line.charAt(offset++);
}
offset = 0;
}
return pic;
Also , you probably want to reset the value of offset after each processed "row".
Scanner fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
pic[i] = line.toCharArray();
i++;
}
fileReader.close();
I tried it with seuqnce and worked:
Scanner fileReader = new Scanner(System.in);
System.out.println(fileReader.nextLine());
fileReader.close();
fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
pic[i] = line.toCharArray();
System.out.println(line);
i++;
}
fileReader .close();
output:
sadsadd sadsadd
sadasdasdasdsad sadasdasdsadsa sadasdasdsadsadsa dAS dASd
Process finished with exit code 0

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.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 need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

combine two methods in Java together in this Java code

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

Getting array index out of bounds exception but don't know why?

I am trying to create a split() method that reads a file, line by line, then separates the Strings and Integers into an array that is then written to another file. I have created an array to hold each String called list and one to hold the Integers called scores.
When I try to run my code, it reaches the second element in the list array which is surname = list[1] and then I get the error.
What I am trying to eventually do is split each element and get the average of the Integers so the original line of text would read Mildred Bush 45 65 45 67 65 and my new line of text would read Bush, Mildred: Final score is x.xx.
The error happens at line 7 surname = list[1];
My code:
public void splitTest()
{
String forename, surname, tempStr, InputFileName, OutputFileName;
tempStr = "";
String[] list = new String[6];
list = tempStr.split(" ");
forename = list[0];
surname = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
clrscr();
System.out.println("Please enter the name of the file that is to be READ (e.g. details.txt) : ");
InputFileName = Genio.getString();
System.out.println("Please enter the name of the file that is to be WRITTEN TO (e.g. newDetails.txt) : ");
OutputFileName = Genio.getString();
try {
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
outputStream = new FileOutputStream(OutputFileName);
printWriter = new PrintWriter(outputStream);
tempStr = bufferedReader.readLine();
while (tempStr != null) {
System.out.println(tempStr);
printWriter.write(tempStr+"\n");
tempStr = bufferedReader.readLine();
}
System.out.println("\n\nYOUR NEW FILE DATA IS DISPLAYED ABOVE!\n\n");
pressKey();
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
System.out.println("Sorry, there has been a problem opening or reading from the file");
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred when attempting to close the file");
}
}
if(printWriter != null) {
printWriter.close();
}
}
}
Where it says Genio, this a class that deals with user input.
You initialize the list array with
list = tempStr.split(" ");
The size of that array can be anything. It depends on the number of spaces in tempStr.
You have to check the length of list before accessing its elements.
If you expect the input to contain a certain number of parameters, add a check :
list = tempStr.split(" ");
int[] scores = new int[5];
if (list.length > 6) {
forename = list[0];
surname = list[1];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
}
This would prevent the exception. Of course, you have to decide how to handle the situation in which the condition is false.
EDIT :
tempStr = "";
This means there would be exactly one element in list. I'm assuming you meant to put some actual value in this variable.

java read integers from text file

I am using eclipse ; I need to read integers from a text file that may have many lines of numbers separated by space : 71 57 99 ...
I need to get these numbers as 71 and 57 ...but my code produces numbers in the range 10 to 57
int size = 0;
int[] spect = null;
try {
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
size = is.available();
spect = new int[size];
for (int si = 0; si < size; si++) {
spect[si] = (int) is.read();// System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print(e.getMessage());
}
read() reads single byte and then you are converting into int value, you need to read line by line using BufferedReader and then split() and Integer.parseInt()
Have you considered using a Scanner to do this? Scanner can take the name of the file as the parameter and can easily read out each individual number.
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
int[] spect = new int[is.available()];
Scanner fileScanner = new Scanner("/dataset.txt");
for(int i = 0; fileScanner.hasNextInt(); i++){
spect[i] = fileScanner.nextInt();
}
You may convert it to a BufferedReader and read and split the lines.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null) {
String[] strings = line.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
//do what you need with the Integer
}
}

Categories