Solucione la advertencia: utiliza o anula una API obsoleta en Java
Hoy, veremos por qué una advertencia dice “usa o anula una API obsoleta” y demostraremos cómo solucionar esto para realizar la tarea.
Arreglar la advertencia que dice usa o anula una API obsoleta en Java
Código de ejemplo (que contiene una advertencia):
// import libraries
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
// Main class
public class Main {
// main method
public static void main(String[] args) {
// path of a text file
File filePath = new File("Files/TestFile.txt");
try {
// obtain input bytes from a file
FileInputStream fileInputStream = new FileInputStream(filePath);
// adds the functionality to another input stream
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
// lets an app read primitive Java data types from the specified input stream
DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);
if (dataInputStream.available() != 0) {
// Get a line.
String line = dataInputStream.readLine();
// Place words to an array which are split by a "space".
String[] stringParts = line.split(" ");
// Initialize the word's maximum length.
int maximumLength = 1;
// iterate over each stingPart, the next one is addressed as "stringX"
for (String stringX : stringParts) {
// If a document contains the word longer than.
if (maximumLength < stringX.length())
// Set the new value for the maximum length.
maximumLength = stringX.length();
} // end for-loop
// +1 because array index starts from "0".
int[] counter = new int[maximumLength + 1];
for (String str : stringParts) {
// Add one to the number of words that length has
counter[str.length()]++;
}
// We are using this kind of loop because we require the "length".
for (int i = 1; i < counter.length; i++) {
System.out.println(i + " letter words: " + counter[i]);
} // end for-loop
} // end if statement
} // end try
catch (IOException ex) {
ex.printStackTrace();
} // end catch
} // end main method
} // end Main class
En este código, accedemos a un archivo .txt, leemos ese archivo línea por línea y colocamos las palabras en una matriz que se divide en función de un solo espacio. Luego, contamos el número de caracteres en cada palabra y los mostramos todos en la salida del programa.
Aunque este programa genera la salida, también destaca que estamos usando o anulando una API obsoleta en la línea String line = dataInputStream.readLine();. Vea lo siguiente.

Esta advertencia se genera utilizando el método readLine() de la clase DataInputStream. Según la documentación, este método ha quedado obsoleto desde JDK 1.1 porque no convierte los bytes en caracteres correctamente.
Aunque el método está en desuso y es probable que funcione como se esperaba en algunos casos. Pero ya no podemos garantizar que cumplirá su función.
Por lo tanto, es bueno usar un método similar pero consistente.
A partir de JDK 1.1, el método preferido para leer las líneas de texto es la función readLine() de la clase BufferedReader. No tenemos que cambiar todo el código desde cero, solo necesitamos convertir el DataInputStream a la clase BufferedReader.
Reemplace esta línea de código:
DataInputStream dataInputStream = new DataInputStream(in);
Con esta línea de código:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
Ahora, el programa de trabajo completo se verá de la siguiente manera.
// import libraries
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
// Main class
public class Main {
// main method
public static void main(String[] args) {
// path of a text file
File filePath = new File("Files/TestFile.txt");
try {
// obtain input bytes from a file
FileInputStream fileInputStream = new FileInputStream(filePath);
// adds the functionality to another input stream
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
// lets an app read primitive Java data types from the specified input stream
// DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(bufferedInputStream));
String line = "";
// get a line and check if it is not null
if ((line = bufferedReader.readLine()) != null) {
// Place words to an array which are split by a "space".
String[] stringParts = line.split(" ");
// Initialize the word's maximum length.
int maximumLength = 1;
// iterate over each stingPart, the next one is addressed as "stringX"
for (String stringX : stringParts) {
// If a document contains the word longer than.
if (maximumLength < stringX.length())
// Set the new value for the maximum length.
maximumLength = stringX.length();
} // end for-loop
// +1 because array index starts from "0".
int[] counter = new int[maximumLength + 1];
for (String str : stringParts) {
// Add one to the number of words that length has
counter[str.length()]++;
}
// We are using this kind of loop because we require the "length".
for (int i = 1; i < counter.length; i++) {
System.out.println(i + " letter words: " + counter[i]);
} // end for-loop
} // end if statement
} // end try
catch (IOException ex) {
ex.printStackTrace();
} // end catch
} // end main method
} // end Main class
Además, si también ve algo similar a lo siguiente.
Recompile with -Xlint: deprecation for details
No te preocupes; simplemente le dice una opción para usar mientras compila para tener más detalles sobre dónde está usando las cosas obsoletas.
