Cấp bậc tác giả:

JAVA

Nhập mảng từ file, sắp xếp và xuất ra file trong Java

Được viết bởi webmaster ngày 10/12/2014 lúc 11:47 PM
Tạo 1 class khơi tạo mảng (class InitArray), Tạo 1 class nhập xuất mảng từ file kế thừa class khởi tạo mảng (class IOArray extends InitArray), Tạo 1 class sắp xếp mảng kế thừa class khởi tạo mảng (class SortArray extends InitArray), Class mảng (Array) chứa hàm main() thực thi chương trình
  • 0
  • 14447

Nhập mảng từ file, sắp xếp và xuất ra file trong Java

- Tạo 1 class khơi tạo mảng (class InitArray)
– Tạo 1 class nhập xuất mảng từ file kế thừa class khởi tạo mảng (class IOArray extends InitArray)
– Tạo 1 class sắp xếp mảng kế thừa class khởi tạo mảng (class SortArray extends InitArray)
– Class mảng (Array) chứa hàm main() thực thi chương trình
Dưới đây là code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
class InitArray
{
    int [] Element;
}
class IOArray extends InitArray
{
    void input_file() throws FileNotFoundException
    {
        FileInputStream fi = new FileInputStream("input.txt");
        Scanner inp = new Scanner(fi,"UTF-8");
        String temp = inp.nextLine(); //doc dong mang trong file
        inp.close();
        String [] item = temp.split(" "); //tach chuoi thanh cac phan tu chuoi
        Element = new int[item.length];
        for(int i=0; i<item.length; i++) //doi kiem string sang int cua cac phan tu
            Element[i] = Integer.parseInt(item[i]);
    }
    void output_file() throws IOException
    {
        FileOutputStream fo = new FileOutputStream("output.txt");
        PrintWriter out = new PrintWriter(fo);
        for (int i=0; i<Element.length; i++)
            out.printf("%-5d",Element[i]);
        out.close();
    }
}
 
class SortArray extends InitArray
{
    public void sort(IOArray A) //phuong thuc sap xep
    {
        Arrays.sort(A.Element);
    }
}
 
class Array
{
    public static void main(String[] args) throws IOException
    {
        IOArray Arr = new IOArray();
        Arr.input_file(); //nhap tu file
        SortArray SArr = new SortArray();
        SArr.sort(Arr); //sap xep
        Arr.output_file(); //xuat ra file
        System.out.println("nSucces ! Open file output.txt to view");
    }
}

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML