How do I add the file line I have edited to the same line I got the contents from my txt file?
1,House mack,house,123 mack road,155,40000,40000,2022-09-29,no,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
2,House John,house,123 John road,183,50000,50000,2022-09-10,yes,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
But my output to the txt file looks like this
1,House mack,house,123 mack road,155,40000,111,2022-09-29,no,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
1,House mack,house,123 mack road,155,40000,111,2022-09-29,no,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
How can I get my program to only replace in the edited line in place of the old line and leave the other file contents alone?
if (option.equals("cp")) {
Array.set(values, 6, newPaid);
findString = "\n" + values[0] + "," + values[1] + "," + values[2] + ","
+ values[3] + "," + values[4] + "," + values[5] + "," + values[6] + ","
+ values[7] + "," + values[8] + "," + values[9] + "," + values[10] + ","
+ values[11] + "," + values[12] + "," + values[13] + "," + values[14] + ","
+ values[15] + "," + values[16] + "," + values[17] + "," + values[18] + ","
+ values[19] + "," + values[20] + ",";
replaceLines(findString);
System.out.println("Your Price has been changed and contents has been successfully updated! ");
break;
My method that contains all the calculations
public static void replaceLines(String findString) {
try {
BufferedReader file = new BufferedReader(new FileReader("tasks.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
line = findString;
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("tasks.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Something prevalent within a specific file record has pointed you to the correct (distinct) record in order to carry out a price change, be it an ID number, a name, an Address, or whatever. You need hold whatever that is. Most would go by a distinct record ID number so that you are only changing the data within that specific record alone otherwise you could potentially change several records within the file.
Within the replaceLines() method, the findString parameter holds a new (modified) data line for the file which is to replace and existing line within the same file. The question here would be....replace what line? You don't pass that information to your method. Change the price for which person, place, or thing? This obviously needs to be determined before any changes can be carried out. For an example, let's say we want to change the price (at index 6) within the file record with an ID of 1, the call to the replaceLines() method should be:
replaceLine( 1, findLines );
What would be easier is if you specified the record, the column that needs changing, and then what the new value might be for that specific column, for example:
updateRecord( 1, 6, "111" );
It could go something like this:
public static void updateRecord(int recordID, int recordColumnIndex, String newValue) throws IOException {
java.io.PrintWriter writer;
try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader("tasks.txt"))) {
writer = new java.io.PrintWriter("temp.tmp");
String line;
// Read file line by line...
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
writer.println(line);
continue;
}
// Split each read line to separate data.
String[] lineParts = line.split("\\s*,\\s*");
/* If the record ID value matches the supplied ID value
then make the desired changes to that line. */
if (Integer.parseInt(lineParts[0]) == recordID) {
lineParts[recordColumnIndex] = newValue;
// Rebuild the data line...
StringBuilder sb = new StringBuilder(String.valueOf(recordID));
for (int i = 1; i < lineParts.length; i++) {
sb.append(",").append(lineParts[i]);
}
line = sb.toString();
}
writer.println(line); // write line to `temp.tmp` file.
writer.flush(); // Immediate write.
}
}
writer.close();
/* Delete the `tasks.txt` file and then rename
`temp.tmp` to `tasks.txt`. */
if (new File("tasks.txt").delete()) {
java.nio.file.Path source = java.nio.file.Paths.get("temp.tmp");
java.nio.file.Files.move(source, source.resolveSibling("tasks.txt"));
}
}
If I'm looking at a list of records originally from the tasks.txt file and I can see that the record with the ID of 1 needs to have a price change in column 7 (index 6) from 40000 to 111 then I would call:
try {
updateRecord(1, 6, "111");
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
On a Side:
Just curious, why do you start your file records with a newline (\n) character and why do you end all your records with a comma (,)??
I am trying to read os-release file on Linux and trying to get the OS version by finding VERSION_ID="12.3" line. I wrote below piece of code but at the last after splitting the string first time I am unable to go further. I reached up to splitting to "12.3" from VERSION_ID, after this I applied split function again and getting "java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 0" error. , Need your help and valuable suggestions.
File fobj2 = new File("C:\\os-release");
if(fobj2.exists() && !fobj2.isDirectory())
{
Scanner sc = new Scanner(fobj2);
while(sc.hasNextLine())
{
String line = sc.nextLine();
//VERSION_ID="12.3"
if(line.contains("VERSION_ID="))
{
System.out.println(" VERSION_ID= " + line );
String [] ver = line.split("=");
if(ver.length > 1)
{
String [] ver_id = line.split("=");
System.out.println(" ver_id.length " + ver_id.length );
System.out.println(" ver_id[0] " + ver_id[0] );
System.out.println(" ver_id[1] " + ver_id[1] );
System.out.println(" ver_id[1].length() " + ver_id[1].length() );
String [] FinalVer1 = ver_id[1].split(".");
System.out.println(" FinalVer1[1].length() " + FinalVer1[1].length() );
System.out.println(" FinalVer1[1] " + FinalVer1[1] );
}
}
}
Here is yet another way to gather the Major and Minor version values from the line String:
String line = "VERSION_ID=\"12.3\"";
// Bring line to lowercase to eliminate possible letter case
// variations (if any) then see if 'version-id' is in the line:
if (line.toLowerCase().contains("version_id")) {
// Remove all whitespaces and double-quotes from line then
// split the line regardless of whether or not there are
// whitespaces before or after the '=' character.
String version = line.replaceAll("[ \"]", "").split("\\s*=\\s*")[1];
//Get version Major.
String major = version.split("[.]")[0];
// Get version Minor.
String minor = version.split("[.]")[1];
// Display contents of all variables
System.out.println("Line: --> " + line);
System.out.println("Version: --> " + version);
System.out.println("Major: --> " + major);
System.out.println("Minor: --> " + minor);
}
Try this !
File fobj2 = new File("C:\\os-release");
if(fobj2.exists() && !fobj2.isDirectory())
{
Scanner sc = new Scanner(fobj2);
while(sc.hasNextLine())
{
String line = sc.nextLine();
//VERSION_ID="12.3"
if(line.contains("VERSION_ID="))
{
System.out.println(" VERSION_ID= " + line );
String [] ver = line.split("=");
if(ver.length > 1)
{
String [] ver_id = line.split("=");
System.out.println(" ver_id.length " + ver_id.length );
System.out.println(" ver_id[0] " + ver_id[0] );
System.out.println(" ver_id[1] " + ver_id[1] );
System.out.println(" ver_id[1].length() " + ver_id[1].length() );
// Here
String [] FinalVer1 = ver_id[1].split("\\.");
System.out.println(" FinalVer1[1].length() " + FinalVer1[1].length() );
System.out.println(" FinalVer1[1] " + FinalVer1[1] );
}
}
}
Just need to escape the dot like this.
I think that when You are using split method on string like "VERSION_ID="12.3"", the output would be: String arr = {"VERSION_ID", "12.3"}. So why are You using the next split with "=" on the ver_id array. Try using ".", from my understanding You are looking for number after the dot.
My program consists of several options of what to do with user input data about shows (name, day, time). One of the options is to read a file and display its content to the user. Although this section of my program is working, it isn't displaying correctly (As shown below). Should I make changes to how the program reads the file? If there are any suggestions on what I should change about my code, I would truly appreciate it! Thank you.
Here is my code:
//Method loadShows
public static void loadShows() throws IOException {
//String to find file
String findFile, file;
//ask for location of file
System.out.println("Enter Show File Location: ");
//Read input
findFile = in.readLine();
file = findFile + "/show.txt";
BufferedReader input = new BufferedReader(new FileReader(file));
x = Integer.valueOf(input.readLine()).intValue();
System.out.println("Loading " + x + " Shows");
for(i = 0; i<=(x-1); i++) {
name[i] = input.readLine();
day[i] = input.readLine();
time[i] = input.readLine();
}
for(i = 0; i<=(x-1); i++) {
System.out.println("Name : " + name[i]);
System.out.println("Day : " + day[i]);
System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
}
}
Here is the output:
Enter Show File Location:
C:\Users\OneDrive\Desktop\MyFirstJavaProject
Loading 3 Shows
Name : //***As you can see it isn't in order, or displayed correctly***
Day : Suits
Time(2:30 am = 0230) : Monday
Name : 0130
Day : The Flash
Time(2:30 am = 0230) : Thursday
Name : 0845
Day : National Geographic
Time(2:30 am = 0230) : Sunday
Here is my file content:
3
Suits
Monday
0130
The Flash
Thursday
0845
National Geographic
Sunday
0525
You can do with only one for:
public static void loadShows() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\adossantos\\file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
String[] values = everything.split("\n");
for(int i = 0; i < values.length; i+=3) {
if(i + 3 > values.length - 1 )
break;
System.out.println("Name : " + values[i + 1]);
System.out.println("Day : " + values[i + 2 ]);
System.out.println("Time(2:30 am = 0230) : " + values[i + 3] + "\r");
}
} finally {
br.close();
}
}
Response:
I am trying to figure out how to make a grep method that can read wrapped phrases from up-to infinity lines(That is a sentence or string spanning multiple lines of a given text file) in java. Here is my current code for the grep function:
public static void grep() throws IOException{
BufferedReader f = new BufferedReader(new FileReader("Cabbages.txt"));
Scanner in = new Scanner(System.in);
String line = "", input = "", wrappedPhrase = "", modified = "";
int c = 0, foundCount = 0;
boolean found = false;
System.out.print("Please enter something you want to grep: ");
input = in.nextLine();
while((line = f.readLine()) != null) {
c++;
found = false;
int index = line.indexOf(input);
while(index >= 0) {
modified = "<" + line.substring(line.indexOf(input), (line.indexOf(input)+input.length())) + ">";
found = true;
index = line.indexOf(input, index + 1);
foundCount++;
}
if(found) {
System.out.println("Found on line: " + c + ", which is: " + line.replace(input, modified));
}
}
if(foundCount <= 0) {
System.out.println("Sorry, the input string of: \"" + input + "\" was not found within the given file.");
}else {
System.out.println("In total, the input string of: \"" + input + "\"" + " was found " + foundCount + " time(s).");
}
}
I am creating a Premier League football table in my spare time and I have come across a problem. While the program runs I want it to be perfect and output in the format I want it to, the problem is:
You enter the the Input (" HomeTeam : AwayTeam : HomeScore : AwayScore ") as follows
When you are done with the list you enter "quit" to stop the program
My issue is that the scores come out like this
(" HomeTeam | AwayTeam | HomeScore | AwayScore ")
I intend it to print like this (" HomeTeam [HomeScore] | AwayTeam [AwayScore] ")
I have tried many variations of System.out.printlns to no avail, even trying to make several Boolean conditions that will output the input in the way I want it too. I am truly at a loss and it is frustrating - I hope that someone can give me tips the code is attached
Edited for loop;
for (int i = 0; i < counter; i++) { // A loop
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + "[" + words[2].trim() + "]" + " | " + words[1].trim() + "[" + words[3].trim()) + "]";
This should work:
Scanner sc = new Scanner(System.in);
public void outputScore(String input) {
String[] words = input.trim().split("\\s+");
String satisfied = sc.nextLine();
if (satisfied.equals("quit")) {
System.out.println(words[0] + " [" + words[4] + "] | " + words[2] + " [" + words[6] + "]");
}
}
This is what the method should look like when you call it:
outputScore(sc.nextLine());
Here is the code to your edited question:
String [] product_list = new String [100];
int counter = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows:");
System.out.println("Home team : Away team : Home score : Away score");
String line = null;
while (!(line = scanner.nextLine()).equals("")) {
if (line.equals("quit")) {
break;
} else {
product_list[counter] = line;
System.out.println("Home team : Away team : Home score : Away score");
}
counter++;
}
for (int i = 0; i < counter; i++) {
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + " : " + words[2].trim() + " | " + words[1].trim() + " : " + words[3].trim());
}
Hope this helps.