简体   繁体   中英

Manipulating table data in Java after reading .txt file using Scanner or Buffer

I am trying to manipulate row and column data in a tilde delimited table contained in a .txt file in Java. I have successfully scanned/read the data but am not sure how to manipulate it to mirror the actions of relational algebra and then writes the output to a new .txt file as a tilde delimited table like the original so that it can then be read by another method like project(). For example I would like to create a restrict() method that will restrict the output to only Toyotas so the main body of a driver program might look like this:

//restrict the cars table to toyotas producing a table named toyotas    
Algebra.Restrict("cars","MAKE='Toyota'","toyotas");  

//project just three columns from the toyotas table producing a table named answer    
Algebra.Project("Toyotas","Make,Model,Price","answer");  

//display the contents of the answer table    
Algebra.Display("answer");

output would be:

MAKE MODEL PRICE
---------------- 
Toyota Camry 18000    
Toyota Tacoma 19000    
Toyota Highlander 35000 

Input from cars.txt

MAKE~MODEL~TYPE~PRICE

Toyota~Camry~Sedan~18000

Toyota~Tacoma~Truck~19000

Ford~Mustang~Sport~21000

Chevrolet~Corvette~Sport~48000

Ford~F150~Truck~25000

Toyota~Highlander~SUV~35000

Using the following code for algebra.Restrict("Ford", "", "Truck");:

   public void Restrict(String a, String b, String c )throws FileNotFoundException, IOException{
    {
        Scanner x = null;
        try
        {
            x = new Scanner(new File("cars.txt"));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        ArrayList<String[]> arr = new ArrayList<String[]>();
        while (x.hasNext())
        {
            String str[] = x.next().split("~");
            arr.add(str);
        }

        for (String[] column : arr)
        {
            if (column[0].equals(a))
            {System.out.println(column[0] + " " + column[1] + " " + column[2]);

                // save table to disk     
                PrintWriter outputfile = new PrintWriter("RestrictTable.txt");
                outputfile.print(column[0] + " " + column[1] + " " + column[2]);
                outputfile.close(); 

            }


        }
        for (String[] column : arr)
        {
            if (column[1].equals(b))
            {System.out.println(column[0] + " " + column[1] + " " + column[2]);

                // save table to disk     
                PrintWriter outputfile = new PrintWriter("RestrictTable.txt");
                outputfile.print(column[0] + " " + column[1] + " " + column[2]);
                outputfile.close(); 

            }



        }
        for (String[] column : arr)
        {
            if (column[2].equals(c))
            {System.out.println(column[0] + " " + column[1] + " " + column[2]);

                // save table to disk     
                PrintWriter outputfile = new PrintWriter("RestrictTable.txt");
                outputfile.print(column[0] + " " + column[1] + " " + column[2]);
                outputfile.close(); 

            }


        }
                        System.out.println("NEW TABLE SAVE TO DISK");




    }


    }
    public void Project(String a)throws FileNotFoundException, IOException{
        {
        Scanner x = null;
        try
        {
            x = new Scanner(new File("cars.txt"));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        ArrayList<String[]> arr = new ArrayList<String[]>();
        while (x.hasNext())
        {
            String str[] = x.next().split("~");
            arr.add(str);
        }

        for (String[] car : arr)
        {
            if (car[0].equals(a))
            {
                System.out.println(car[0] + " " + car[1] + " " + car[2]);

                // save table to disk     
                PrintWriter outputfile = new PrintWriter("ProjectTable.txt");
                outputfile.print(car[0] + " " + car[1] + " " + car[2]);
                outputfile.close(); 

            }

        }
                        System.out.println("NEW TABLE SAVED TO DISK / ProjectTable.txt");




    }


    }

Output I get:

Ford Mustang Sport
Ford F150 Truck
Toyota Tacoma Truck
Ford F150 Truck
NEW TABLE SAVE TO DISK

desired output

MAKE~MODEL~TYPE
Ford~F150~Truck
NEW TABLE SAVE TO DISK

or at the very least

Ford F150 Truck
NEW TABLE SAVE TO DISK

Use can use streams (requires Java 8). This is a mapping of relational algebra operations that you mentioned to methods of Stream :

  • Restrict: filter

  • Project: map

  • Display: collect

You have to be aware of the disadvantages of your approach in comparison to a relational database management system:

  • Requires a lot of memory in case of much data (does not scale well)

  • No query optimization

  • No indexes

  • No transactions

  • No constraints

Step 1) Read the data into a variable and create a data object. The simplest is an array and list, better if you create car class and create a key value pairing but for simplicity here is a potential solution.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class cars
{

    public static void main(String[] args)
    {
        Scanner x = null;
        try
        {
            x = new Scanner(new File("cars.txt"));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        ArrayList<String[]> arr = new ArrayList<String[]>();
        while (x.hasNext())
        {
            String str[] = x.next().split("~");
            arr.add(str);
        }

        for (String[] car : arr)
        {
            if (car[0].equals("Toyota"))
            {
                System.out.println(car[0] + " " + car[1] + " " + car[2] + " " + car[3]);
            }
        }
    }
}

Output:

Toyota Camry Sedan 18000
Toyota Tacoma Truck 19000
Toyota Highlander SUV 35000

I did this in 5minutes but you can easily use it as a template to make methods restrict . Template would be similar to.

private boolean restrictBy (String make){
  if make.equals("Totota") {
    return true;
  } else {
    return false;
  }
}

EDIT:

File outFile = new File ("output.txt");
FileWriter fWriter = null;
try { fWriter = new FileWriter (outFile); }
catch (IOException e) { e.printStackTrace(); }
PrintWriter pWriter = new PrintWriter (fWriter);
for (String[] car : arr)
{
    if (restrictBy(car, "Ford" , "", "Truck"))
    {
        System.out.println(car[0] + " " + car[1] + " " + car[2] + " " + car[3]);
        pWriter.println(car[0] + " " + car[1] + " " + car[2] + " " + car[3]);
    }
}
pWriter.close();    

and the method restrictBy

private static boolean restrictBy (String[] car, String make, String model, String type) {
    boolean filtered = true;
    if (make.length() > 0 && !car[0].equals(make))
    {
        filtered = false;
    }
    if (model.length() > 0 && !car[1].equals(model))
    {
        filtered = false;
    }
    if (type.length() > 0 && !car[2].equals(type))
    {
        filtered = false;
    }
    return filtered;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM