• 0

[JAVA] Replacing a text in a text file.


Question

Hi guys, I have another problem at hand now hope you guys can help me.

I have a text file as shown below.

  Quote
Mark:123:Red

Paul:746:Yellow

Ginger:447:Blue

I have a method to read in the text file and print out the line accoding to the user name.

eg. if user name is Paul, i will print out "PAUL:746:YELLOW".

Now I will like to edit YELLOW to ORANGE and then put it back to the text file in the same line.

it SHOULD look like this.

  Quote
Mark:123:Red

Paul:746:Orange

Ginger:447:Blue

The only solution i can think of is using a temp file to copy it over. Is there any other faster implementation or better ones ?

Link to comment
https://www.neowin.net/forum/topic/630880-java-replacing-a-text-in-a-text-file/
Share on other sites

10 answers to this question

Recommended Posts

  • 0

I'm new at Java, so shoot me if it's wrong but it's just an idea I would use.. 'ReadFile' to read the txt file, BufferedReader to go over the lines, add the lines to some sort of a Collection or just String[]. Then go over that Collection/ String[] again with a for each or something then use the replace/replaceAll() methods of String and eventually write every line back with FileOutputStream. (The last two, string replace / write output can be combined since you'll need to go over every line again anyway to write it out.

Hope it helps a bit :)

  • 0

Read into memory, make changes, write back to disk.

You'll find that there are no advantages to doing it in-place on the disk. In fact, reading bytes (as in single characters) from a disk is a great deal slower than reading a lot more... reading clusters at a time which varies from format to format but is certainly a lot more than thousands of characters at a time.

In the context of an academic exercise like this... they probably want you to use the java File classes and/maybe StringTokenizer... :)

Enjoy!

  • 0

Try something like this (I just wrote it in the reply box, it's untested):

try {
	BufferedReader in = new BufferedReader(new FileReader("in.txt"));
	PrintWriter out = new PrintWriter(new File("out.txt"));

	String line; //a line in the file
	String params[]; //holds the name:number:color parameters of each line

	while ((line = in.readLine()) != null) {
		params = line.split(":", 3); //split the line into the 3 parameters seperated by :
		if (params[0] == "Paul" && params[1] == "746") { //find the line we want to replace
			out.println(params[0] + ":" + params[1] + ":" + "Orange"); //output the new line
		} else {
			out.println(line); //if it's not the line, just output it as-is
		}
	}

	in.close();
	out.flush();
	out.close();
} catch (Exception e) {
	e.printStackTrace();
}

  • 0
  Poolius said:
Can you use logical equals (==) on string types in Java now? I thought you had to use .equals() as == checked memory references? I realise I'm being a bit trivial, the code kindly provided appears pretty sound :) .

No, you still should be using .equals()

Might work, but "best practices"...

  • 0

Oh sorry, lol :fun:

try {
	BufferedReader in = new BufferedReader(new FileReader("in.txt"));
	PrintWriter out = new PrintWriter(new File("out.txt"));

	String line; //a line in the file
	String params[]; //holds the name:number:color parameters of each line

	while ((line = in.readLine()) != null) {
		params = line.split(":", 3); //split the line into the 3 parameters seperated by :
		if ("Paul".equals(params[0]) && "746".equals(params[1])) { //find the line we want to replace
			out.println(params[0] + ":" + params[1] + ":" + "Orange"); //output the new line
		} else {
			out.println(line); //if it's not the line, just output it as-is
		}
	}

	in.close();
	out.flush();
	out.close();
} catch (Exception e) {
	e.printStackTrace();
}

PS, when you use "literal".equals(stringObj), you won't get a runtime error if stringObj is null (unlike stringObj.equals("literal")).

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I don't care about browser benchmarks. It's loads pages nearly instantly and doesn't really feel slow at all to me. Anyway I care more about features and stability and so far I'm satisfied. Plus I wouldn't use Edge if Microsoft paid me.
    • And the big problem we have seen with government organizations is the incredibly slow accountability. In the private space, the need to turn a profit forces the issue. That may not always be healthy, but it is swift. The best working example of a government organization is the USPS, but that is in part because it was created to operate like a business, with its own budget and revenue. That model may not work in every case, for example, I wouldn't want law enforcement under pressure to find revenue, but in some cases it does work.
    • Hell Let Loose, and A Little to the Left, and more join Xbox Free Play Days this weekend by Pulasthi Ariyasinghe Microsoft lets every Game Pass subscriber jump into fresh games every weekend for no extra cost, and it's time for another bunch of games to join the fray. The latest update offers Xbox Game Pass Ultimate, Standard, and Core subscribers access to three games: Dragon Ball Xenoverse 2, Hell Let Loose, and A Little to the Left. As usual, any progress made during the weekend also carries over automatically if you decide to purchase a game afterward. From the trio, Hell Let Loose is for shooter fans, offering 50 versus 50 PVP battles across various realistic World War II fronts. However, the gameplay is a much more hardcore experience compared to other shooters on the market. The title features infantry, tanks, and artillery warfare, with 14 roles available that offer different weapons and teamwork-related equipment. Next, Dragon Ball Xenoverse 2 comes in, touting its ties to the massive anime franchise. The title has players time-traveling to the past as a custom Dragon Ball character to make sure historical moments from the storyline happen just as fans remember. While the world itself is a massive one, fights happen in 3D arenas, taking cues from notable locations in the anime universe. If both those games are a bit too action-heavy, A Little to the Left is a cozy puzzle experience that aims to settle your perfectionist needs. The game has you sorting, stacking, and organizing household items from their awkward locations to more pleasing and organized placements. The controls mostly involve drag-and-drop operations, and some puzzles even have multiple solutions for neatness. Here are the three latest Free Play Days games and their supported platforms: Hell Let Loose - $24.99 (Xbox Series X|S, PC) DRAGON BALL XENOVERSE 2 - $5.99 (Xbox Series X|S, Xbox One, PC) A Little to the Left - $7.49 (Xbox Series X|S, Xbox One, PC) This Free Play Days promotion will end on Sunday, June 8, at 11:59 pm PT. Following this, expect another round of games to enter the program next Thursday.
    • AMD 25.6.1 driver out with RX 9060 XT support and a lot more FSR 4 games by Pulasthi Ariyasinghe A brand-new hardware launch is happening today for AMD, and to make sure its new GPUs are running properly, a new graphics driver has also landed right alongside it. The AMD Software: Adrenalin Edition 25.6.1 driver lands with support for the RX 9060 XT and the AMD Radeon AI PRO R9700, while also finally updating the number of games that support its AMD FidelityFX Super Resolution 4 upscaling technology. The consumer space-targeted RX 9060 XT graphics card comes in 8GB and 16GB flavors starting at $300 and $350 price points, respectively. Check out our launch coverage for this RDNA 4 GPU for more details here. At the same time, the AMD Radeon AI PRO R9700 comes in for handling professional workloads with a whopping 32GB of VRAM. While support for this card has already arrived with the latest driver, AMD is expecting to ship the product sometime in July 2025. The driver has also added official support for Onimusha 2: Samurai's Destiny Remaster as well, the Capcom-developed action game from last month. As for fixes, AMD has said that it has resolved reversed Quality and Performance selections in the Radeon Boost UI, as well as Le Mans Ultimate performance issues on RX 9070 series GPUs. There are quite a few known issues AMD is still working on: Stutter and lower than expected performance may be observed when using alt-tab and streaming to Discord with multiple monitors. Intermittent application crash or driver timeout may be observed while playing Marvel Spiderman 2 with Ray Tracing enabled on Radeon™ RX 9060 XT. Intermittent application crash may be observed when first launching The Last of Us Part 1 on Radeon™ RX 9060 XT graphics products. Stutter may be observed while playing games with some VR headsets at 80Hz or 90Hz refresh rate on some AMD Radeon™ Graphics Products such as the Radeon™ RX 7000 series. Users experiencing this issue are recommended to change the refresh rate as a temporary workaround. Intermittent system or application crash may be observed while playing Cyberpunk 2077 on some AMD Radeon™ Graphics Products such as the Radeon™ RX 7000 series. Intermittent application crash or driver timeout may be observed while playing Monster Hunter Wilds with Radeon™ Anti-Lag and Instant Replay enabled. Artifacts or corruption may appear while playing Battlefield™ V on Radeon™ RX 7000 series graphics products. Stutter may be observed while playing Call of Duty®: Warzone™ Season 03 ‘Verdansk’ map on some AMD Graphics Products. Stutter and lower than expected performance may be observed while playing 4K resolution YouTube videos in Chromium. Users experiencing this issue are recommended to play videos in full screen as a temporary workaround. Texture flickering or corruption may appear while playing The Elder Scrolls IV: Oblivion Remastered with AMD FidelityFX™ Super Resolution enabled on Radeon™ RX 9070 XT. Users experiencing this issue are recommended to disable AMD FidelityFX™ Super Resolution as a temporary workaround. As for FSR 4, these games are now supported by the popular upscaling tech for gaining more frames: Deadzone: Rogue Rem Survival F1 25 Runescape: Dragonwilds Frostpunk 2 Star Wars Outlaws Legacy: Steel & Sorcery Steel Seed Lords of the Fallen Stellar Blade Planetaries Virtua Fighter 5 R.E.V.O QANGA Wild Assault The complete list of games with FSR 4 support, as well as upcoming implementations, can be found on AMD's support page here. The WHQL-certified AMD Software: Adrenalin Edition 25.6.1 driver can now be downloaded from the AMD Software app as well as the changelog page on its official website here.
  • Recent Achievements

    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      406
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      176
    4. 4
      ATLien_0
      170
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!