Java File Infection Simulation and Implementation
Classified in Computers
Written on in
English with a size of 2.8 KB
This document details the implementation of a Virus class in Java, focusing on binary file manipulation and stream handling.
Java Source Code for Virus Simulation
import java.io.*;
import java.util.*;
/**
* Write a description of class Virus here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Virus
{
// Campos
private File virusFile; // Fichero con el código binario del virus
public static final int SIZE = 100;
/**
* Constructor for objects of class Virus
*/
public Virus( String nombre )
{
this.virusFile = new File(nombre);
}
/**
* Método get para el campo this.virusFile
*
* @return this.virusFile
*/
public File getFile()
{
return this.virusFile;
}
/**
* Método que infecta el fichero dado como parámetro. El proceso de infección utilizado se explica en el enunciado
* de la práctica.
*
* @param nombre fichero por infectar
*/
public void InfectarFichero( String nombre )
{
File f = new File(nombre);
long t = f.length();
int pos;
Random gen = new Random();
pos = gen.nextInt((int)t)/SIZE;
System.out.println("El virus se inserta en el bloque " + pos);
try{
FileInputStream vin = new FileInputStream(this.virusFile);
FileInputStream in = new FileInputStream(f);
FileOutputStream out = new FileOutputStream("infectado");
int nleido = 0;
byte [] buffer = new byte[SIZE];
for ( int i = 0 ; i < pos; i++){
if( (nleido = in.read (buffer)) != -1)
out.write(buffer , 0 ,nleido);
}
buffer = new byte[1024];
while( (nleido = vin.read(buffer)) != -1){
out.write(buffer, 0, nleido);
}
while( (nleido = in.read(buffer)) != -1){
out.write(buffer, 0 , nleido);
}
in.close();
vin.close();
out.close();
}catch(FileNotFoundException e){
System.out.println("No existe el fichero");
}catch(IOException e){
System.out.println("Error E/S");
}
}
public static void main( String args[] )
{
Virus v = new Virus( "Fundamentos.virus");
v.InfectarFichero("Actividad6_2_Virus.pdf" );
}
}Key Functionalities
- File Handling: Utilizes FileInputStream and FileOutputStream for binary data.
- Random Insertion: Determines a random block position for the infection.
- Exception Management: Implements try-catch blocks for robust error handling.