Delete java update files

Java, delete / update the line from the file by id

I am studying Java. Can you criticize my code and tell me what I need to do to make it better? I have code that reads a txt file(product base). It contains tabular data where lines are formatted as: id productName price quantity We launch the code with: -u id productName price quantity — update line; or -d id — delete line. So the logic is to find this line, create new File with updated line or without it, delete base file and rename new file. Last important thing: every element on textbase has own weight. It’s int []argsLength . If the element size less that its weight, we fill empty space with whitespaces. simple for test(indents is correct):

1 Recorder 100.00 12 212 Rocket 182.00 400 99333 Hat 4500.00 5 1984711 Crocodile 2.5 4339 13247983Pistol 53500.903 

main:

public class CRUD < public static void main(String[] args) < try < BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String filename = reader.readLine(); BufferedReader fileReader = new BufferedReader(new FileReader(filename)); int[] argsLength = new int[]; FileCreator creator = new FileCreatorFactory().getFileCreator(args[0], args, argsLength, filename); String line; if (creator == null) < System.out.println("Unknow command"); return; >if ((line = creator.isLineIsset()) == null) < System.out.println("Unknow ID"); return; >File resultFile = creator.createNewFile(line); if (resultFile.length() == 0) < System.out.println("Error"); return; >reader.close(); fileReader.close(); Files.delete(new File(filename).toPath()); System.out.println("Result:" + (resultFile.renameTo(new File(filename)))); > catch (IOException e) < e.printStackTrace(); >> > 

FileCreatorFactory:

package ru.kirstentasks.filecreator; public class FileCreatorFactory < public FileCreator getFileCreator(String arg,String[] args, int[] argsMaxLength,String filename) < switch (arg) < case "-u": return new idUpdater(filename,args,argsMaxLength); case "-d": return new idDeleter(filename,args,argsMaxLength); default: return null; >> > 

FileCreator:

public abstract class FileCreator < protected String[] args; protected int[] argsMaxLength; protected String fileName; FileCreator(String fileName, String[] args, int[] argsMaxLength) < this.args = args; this.argsMaxLength = argsMaxLength; this.fileName = fileName; >public String isLineIsset() throws IOException < String result; BufferedReader reader = new BufferedReader(new FileReader(fileName)); while (!((result = reader.readLine()) == null)) < if (args[1].trim().equals(result.substring(0, argsMaxLength[1]).trim())) < reader.close(); return result; >> reader.close(); return null; > public abstract File createNewFile(String line); > 

idDeleter:

package ru.kirstentasks.filecreator; import java.io.*; public class idDeleter extends FileCreator < private String fileName; idDeleter(String fileName, String[] args, int[] argsMaxLength) < super(fileName, args, argsMaxLength); this.fileName = fileName; >@Override public File createNewFile(String line) < BufferedReader fileReader; BufferedWriter fileWriter; File tempFile = new File(fileName + ".temp"); try < fileReader = new BufferedReader(new FileReader(fileName)); fileWriter = new BufferedWriter(new FileWriter(tempFile)); String temp; while (!((temp = fileReader.readLine()) == null)) < if (temp.equals(line)) < continue; >fileWriter.write(temp); fileWriter.newLine(); > fileReader.close(); fileWriter.close(); > catch (IOException e) < e.printStackTrace(); >return tempFile; > > 

idUpdater:

package ru.kirstentasks.filecreator; import java.io.*; public class idUpdater extends FileCreator < private String filename; idUpdater(String filename, String[] args, int[] argsMaxLength) < super(filename, args, argsMaxLength); this.filename = filename; >@Override public File createNewFile(String line) < BufferedReader fileReader; BufferedWriter fileWriter; File tempFile = new File(filename + ".temp"); try < fileReader = new BufferedReader(new FileReader(filename)); fileWriter = new BufferedWriter(new FileWriter(tempFile)); String temp; while (!((temp = fileReader.readLine()) == null)) < if (temp.equals(line)) < temp = createLine(args, argsMaxLength); >fileWriter.write(temp); fileWriter.newLine(); > fileReader.close(); fileWriter.close(); > catch (IOException e) < e.printStackTrace(); >return tempFile; > private String createLine(String[] args, int[] argsLength) < if (args.length != argsLength.length) < return null; >StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.length; i++) < sb.append(String.format("%-" + argsLength[i] + "s", args[i])); >return sb.toString(); > > 

2 Answers 2

  • Classes in Java begin with a capital letter. The use of multi-caps acronyms is discouraged as they are difficult to read. Prefer Crud to CRUD and IdUpdater to idUpdater .
  • You must always close readers that you open. The preferred way to do this is with a try-with-resources block. Old-school is to use a try-finally construct.
  • A product seems like a top-level thing that should possibly be represented by an object rather than a String[] . This problem is small enough that it might be overkill to create an object, but it does make things easier.
  • The idea of having separate actions that encapsulate deleting and updating is sound, but the implementation could use some work, since the parent class has multiple concepts that only apply to one or the other. You can go a long way with a simple one-method interface, since most of the code is really shared between the two operations. The only difference is what you do when you find a matching line. Everything else is duplicated.
  • Don’t use a public class with a package-private constructor unless you need to. You can make the class package-private also.
  • The factory class is probably overkill for just two arguments.
  • You’re not really handling IOException at all, so you may as well let it percolate out. The final output will be the same either way.
Читайте также:  Python import module from another package

I took a quick stab at applying my suggestions to your existing code. The end result (untested) looks like:

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.util.Scanner; public final class Crud < public static void main(final String[] args) throws IOException < final ProductHandler productHandler; switch(args[0]) < case "-u": productHandler = new IdUpdater(new Product(new String[] < args[1], args[2], args[3], args[4]>)); break; case "-d": productHandler = new IdDeleter(args[1]); break; default: System.out.println("Unknown command: " + args[0]); return; > final File file = new File(filename()); final File tempFile = File.createTempFile("", ""); try (final Scanner console = new Scanner(System.in); final FileReader fileReader = new FileReader(file); final BufferedReader bufferedReader = new BufferedReader(fileReader); final FileWriter fileWriter = new FileWriter(tempFile); final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) < boolean found = false; String line; while ((line = bufferedReader.readLine()) != null) < final Product product = new Product(line); found |= productHandler.handle(product, bufferedWriter); >if (!found) < System.out.println("No id matching '" + args[1] + "' found"); >Files.delete(file.toPath()); System.out.println("Result:" + (tempFile.renameTo(file))); > > private static String filename() < try (final Scanner scanner = new Scanner(System.in)) < return scanner.nextLine(); >> > 
import java.io.IOException; import java.io.Writer; class IdDeleter implements ProductHandler < private final String id; IdDeleter(final String id) < this.id = id; >@Override public boolean handle(final Product product, final Writer writer) throws IOException < if (product.hasId(this.id)) < return true; >writer.write(product.asString()); return false; > > 
import java.io.IOException; import java.io.Writer; final class IdUpdater implements ProductHandler < private final Product updatedProduct; public IdUpdater(final Product updatedProduct) < this.updatedProduct = updatedProduct; >@Override public boolean handle(final Product product, final Writer writer) throws IOException < if (product.sharesIdWith(this.updatedProduct)) < writer.write(this.updatedProduct.asString()); return true; >writer.write(product.asString()); return false; > > 
final class Product < private static final int[] COLUMN_SIZES = < 8, 30, 8, 4 >; private final String id; private final String product; public Product(final String product) < this.product = product; this.id = this.product.substring(0, COLUMN_SIZES[0] - 1).trim(); >public Product(final String[] product) < final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < product.length; i++) < stringBuilder.append(String.format("%-" + COLUMN_SIZES[i] + "s", product[i])); >this.product = stringBuilder.toString(); this.id = this.product.substring(0, COLUMN_SIZES[0] - 1).trim(); > public boolean hasId(final String id) < return this.id.equals(id); >public boolean sharesIdWith(final Product product) < return this.id.equals(product.id); >public String asString() < return this.product; >> 
import java.io.IOException; import java.io.Writer; interface ProductHandler

Источник

Читайте также:  Python telegram bot send message to channel

How do I delete old Java versions?

Click Start, point to Settings, and then click the Control Panel. In the Control Panel, double-click the Add/Remove Programs. On the Install/Uninstall tab, click the Java version you want to uninstall, and then click Add/Remove. When you are prompted to continue with the Uninstall, click Yes.

Can I uninstall older versions of Java?

You can uninstall older versions of Java manually in the same way as you would uninstall any other software from your Windows computer. Older versions of Java may appear in the program list as J2SE, Java 2, Java SE or Java Runtime Environment.

How do I uninstall old Java on Windows 10?

Go to the Windows Start Button and select Settings then Control Panel. Click Add or Remove Programs in the Control Panel list. Find Java in the list and uninstall it.

Why can’t i delete Java?

Only Java versions installed using the Java installer are detected. If Java is bundled with any application that uses its own installer, that version of Java will not be offered for removal.

How do I uninstall a previous version of JDK?

  1. Click Programs and Features.
  2. Select Java Card Development Kit from the list of programs.
  3. Click Uninstall and then Finish.

How To Uninstall Older Versions Of Java On Windows 10

How to degrade JDK version?

  1. Click Start.
  2. Select Control Panel.
  3. Click the Add/Remove Programs control panel icon.
  4. The Add/Remove control panel displays a list of software on your system, including any Java software products that are on your computer. Select any that you want to uninstall by clicking on it, and then click the Remove button.

Do I need to uninstall old JDK before installing JDK?

The system will not install a JRE that has an earlier version than the current version. If you want to install an earlier version, then you must first uninstall the existing version.

Do I need to delete old Java?

Keeping old versions of Java on your system presents a serious security risk. Uninstalling older versions of Java from your system ensures that Java applications will run with the latest security and performance improvements on your system.

How do I clean up Java?

  1. In the Java Control Panel, under the General tab, click Settings under the Temporary Internet Files section. .
  2. Click Delete Files on the Temporary Files Settings dialog. .
  3. Click OK on the Delete Files and Applications dialog.

How to uninstall Java from command line?

  1. The following command uninstalls the 32-bit JRE, version 1.8.0_25: msiexec /x
  2. The following command uninstalls the 64-bit JRE, version 1.8.0_25: msiexec /x

Can you have two different versions of Java installed?

Of course you can use multiple versions of Java under Windows and different applications can use different Java versions. This article explains how to run multiple versions of Java side-by-side on the same Windows machine. First of all, the order in which you install the Java Runtime Environments is really important.

Do I still need Java on Windows 10?

You only need Java if an app requires it. The app will prompt you. So, yes, you can uninstall it and it’s likely safer if you do.

How to change the Java version?

  1. Step 1: Press the Windows key and type configure java. .
  2. Step 2: Press the enter key or click on the Configure Java program. .
  3. Step 3: In the Java Control Panel dialog box, click on the Update tab. .
  4. Step 4: Click on the Install button.
  5. Step 5: Click on the Uninstall button to uninstall the older version.

How do I delete old versions?

  1. Press the Windows logo key on your keyboard, then select Settings > System > Storage. Open Storage Settings.
  2. Under your hard drive information, select Temporary files.
  3. Select the Previous version of Windows check box, and then select Remove files.
Читайте также:  Функция возвращающая два значения питон

Can I delete old Java update files?

You can uninstall older versions of Java manually in the same way as you would uninstall any other software from your Windows computer. Older versions of Java may appear in the program list as J2SE, Java 2, Java SE or Java Runtime Environment.

Can I delete older versions of applications?

You can uninstall apps that you’ve installed on your phone. If you remove an app that you paid for, you can reinstall it later without buying it again. You can also disable system apps that came with your phone. Important: You’re using an older Android version.

How to dump out of memory Java?

The memory dump can be created in two ways: By adding “-XX:+HeapDumpOnOutOfMemoryError” to your java start command, like this: java -XX:+HeapDumpOnOutOfMemoryError -Xmx512m … When you start your JVM like this, whenever the first OutOfMemoryError (OOM) is thrown by the JVM, full memory dump will be written to the disk.

What is Java cleaner?

Cleaner manages a set of object references and corresponding cleaning actions. Cleaning actions are registered to run after the cleaner is notified that the object has become phantom reachable. The cleaner uses PhantomReference and ReferenceQueue to be notified when the reachability changes.

How to clear memory in Java program?

In Java, the programmer allocates memory by creating a new object. There is no way to de-allocate that memory. Periodically the Garbage Collector sweeps through the memory allocated to the program, and determines which objects it can safely destroy, therefore releasing the memory.

What happens if I don’t update my Java?

Each version has security issues; the older the version, the more holes it has. And Oracle will no longer patch those. Companies that don’t update Java will be more vulnerable to data leakage and other security weaknesses. The number of security and performance issues that are fixed regularly is vast.

Do you still need Java on your computer?

New, innovative products and digital services designed for the future continue to rely on Java, as well. While most modern Java applications combine the Java runtime and application together, there are still many applications and even some websites that will not function unless you have a desktop Java installed.

What is the difference between remove and delete Java?

Remove and Delete are defined quite similarly, but the main difference between them is that delete means erase (i.e. rendered nonexistent or nonrecoverable), while remove denotes take away and set aside (but kept in existence).

How do I uninstall JDK and JRE?

You can uninstall the JRE by using either the Java Removal Tool or the Java Uninstall tool. To uninstall the JRE, with the Java Removal Tool, use the Add/Remove Programs utility in the Microsoft Windows Control Panel.

Do you need both Java and JDK?

If you want to run Java programs, but not develop them, download the JRE. If you want to develop Java applications, download the Java Development Kit, or JDK. The JDK includes the JRE, so you do not have to download both separately.

What is the difference between Java and JDK installation?

JDK is for development purpose whereas JRE is for running the java programs. JDK and JRE both contains JVM so that we can run our java program. JVM is the heart of java programming language and provides platform independence.

Источник

Оцените статью