Java: Solution phần Java IO

Link Câu hỏi và bài tập: https://v1study.com/java-cau-hoi-va-bai-tap-phan-i-o.html

Solution phần câu hỏi

1. Lớp và phương thức nào bạn sẽ sử dụng để đọc một số mẩu dữ liệu có vị trí gần cuối của một tập tin lớn?

Trả lời: Files.newByteChannel trả về một thể hiện kiểu SeekableByteChannel sẽ cho phép bạn đọc từ (hoặc ghi tới) bất kỳ vị trí nào của tập tin.

2. Khi nào thì cần gọi format và cách tốt nhất để chỉ ra một dòng mới là gì?

Trả lời: Bạn hãy sử dụng %n\n không phải là nền tảng độc lập.

3. Bạn sẽ xác định kiểu MIME của tập tin bằng cách nào?

Trả lời: Phương thức Files.probeContentType sử dụng bộ phát hiện kiểu file bên dưới của nền tảng để đánh giá và trả về kiểu MIME.

4. Phương thức nào bạn sẽ sử dụng để xác định một file có phải là một liên kết biểu tượng hay không?

Trả lời: Bạn sẽ sử dụng phương thức Files.isSymbolicLink.

Solution phần bài tập

Bài tập 1

Viết một ví dụ đếm số lần xuất hiện của một ký tự nào đó trong file. Ký tự bạn có thể nhập từ bàn phím, còn file bạn tự tạo và đưa nội dung vào.

Đáp án tham khảo:

import java.io.*;
import java.nio.file.*;

public class CountLetter {
    private char lookFor;
    private Path file;

    CountLetter(char lookFor, Path file) {
        this.lookFor = lookFor;
        this.file = file;
    }

    public int count() throws IOException {
        int count = 0;
        try (InputStream in = Files.newInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
            {
            String line = null;
            while ((line = reader.readLine()) != null) {
                for (int i = 0; i < line.length(); i++) {
                    if (lookFor == line.charAt(i)) {
                        count++;
                    }
                }
            }
        } catch (IOException x) {
            System.err.println(x);
        }
        return count;
    }

    static void usage() {
        System.out.println(“usage: java CountLetter <letter>”);
        System.exit(-1);
    }

    public static void main(String[] args) throws IOException {

        if (args.length != 1 || args[0].length() != 1)
            usage();

        char lookFor = args[0].charAt(0);
        Path file = Paths.get(“xanadu.txt”);
        int count = new CountLetter(lookFor, file).count();
        System.out.format(“File ‘%s’ has %d instances of letter ‘%c’.%n”,
                file, count, lookFor);
    }
}

Bài tập 2

Một file nào đó chứa dữ liệu bắt đầu bằng một giá trị kiểu long và nó cho bạn biết offset của một giá trị kiểu int. Viết một chương trình lấy và hiển thị phần dữ liệu kiểu int đó.

Đáp án tham khảo:

import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.channels.*;

public class FindInt {
    private Path file;

    FindInt(Path file) {
        this.file = file;
    }

    public int seek() throws IOException {
        int num = -1;

        try (SeekableByteChannel fc = Files.newByteChannel(file)) {

            ByteBuffer buf = ByteBuffer.allocate(8);

            //Get the offset into the file.
            fc.read(buf);
            long offset = buf.getLong(0);

            //Seek to the offset location.
            fc.position(offset);
            buf.rewind();

            //Read the ‘secret’ value.
            fc.read(buf);
            num = buf.getInt(0);
        } catch (IOException x) {
            System.err.println(x);
        }
        return num;
    }

    public static void main(String[] args) throws IOException {
        Path file = Paths.get(“datafile”);
        int num = new FindInt(file).seek();
        System.out.println(“The value is ” + num);
    }
}

Bài tập 3 (dựa trên bài làm của bạn Huy Tuấn)

File NhanVien.java:

package

baitap_iofile.baitap3

;

import

java.io.BufferedReader

;

import

java.io.IOException

;

import

java.io.InputStreamReader

;

public class

NhanVien

{

String

maNV

;

String

hoTen

;

int

tuoi

;

float

luong

;

NhanVien

() {

maNV

=

"1"

;

hoTen

=

"ABCD"

;

tuoi

=

19

;

luong

=

100000000

; }

public

NhanVien

(

String

maNV,

String

hoTen,

int

tuoi,

float

luong) {

this

.

maNV

= maNV;

this

.

hoTen

= hoTen;

this

.

tuoi

= tuoi;

this

.

luong

= luong; }

public

String

getMaNV

() {

return

maNV

; }

public

String

getHoTen

() {

return

hoTen

; }

public int

getTuoi

() {

return

tuoi

; }

public float

getLuong

() {

return

luong

; }

public void

setMaNV

(

String

maNV) {

this

.

maNV

= maNV; }

public void

setHoTen

(

String

hoTen) {

this

.

hoTen

= hoTen; }

public void

setTuoi

(

int

tuoi) {

this

.

tuoi

= tuoi; }

public void

setLuong

(

float

luong) {

this

.

luong

= luong; }

@Override

public

String

toString

() {

return

"NhanVien{"

+

"maNV='"

+

maNV

+

'

\'

'

+

", hoTen='"

+

hoTen

+

'

\'

'

+

", tuoi="

+

tuoi

+

", luong="

+

luong

+

'}'

; }

String

input

()

throws

IOException

{

BufferedReader reader

=

new

BufferedReader(

new

InputStreamReader(

System

.in));

do

{

System

.out.print(

"Enter ID: "

);

maNV

=

reader

.readLine(); }

while

(

maNV

==

null

);

do

{

System

.out.print(

"Enter Full Name: "

);

hoTen

=

reader

.readLine(); }

while

(

maNV

==

null

);

do

{

System

.out.print(

"Enter Age: "

);

tuoi

=

Integer

.parseInt(

reader

.readLine()); }

while

(

tuoi

<=

18

);

System

.out.print(

"Enter Salary: "

);

luong

=

Float

.parseFloat(

reader

.readLine());

return

toString(); } }

File Write_to_file.java:

package

baitap_iofile.baitap3

;

import

java.io.

*;

public class

Write_to_file

{

public static void

main

(

String

[] args)

throws

IOException

{

NhanVien nhanVien

=

new

NhanVien();

BufferedWriter

out =

null

;

try

{ out =

new

BufferedWriter(

new

FileWriter(

"nhanvien.txt"

));

BufferedReader reader

=

new

BufferedReader(

new

InputStreamReader(

System

.in));

int

n;

do

{

System

.out.print(

"Input numbers of employee: "

); n =

Integer

.parseInt(

reader

.readLine()); }

while

(n <=

0

);

for

(

int

i =

0

; i < n; i++) { out.write(

nhanVien

.input()); out.newLine(); } }

finally

{

if

(out !=

null

) { out.close(); } } } }

File Read_from_file.java:

package

baitap_iofile.baitap3

;

import

java.io.BufferedReader

;

import

java.io.FileReader

;

import

java.io.IOException

;

public class

Read_from_file

{

public static void

main

(

String

[] args)

throws

IOException

{

BufferedReader

in =

null

;

try

{ in =

new

BufferedReader(

new

FileReader(

"nhanvien.txt"

));

String

textInALine;

while

((textInALine = in.readLine()) !=

null

) {

System

.out.println(textInALine); } }

finally

{

if

(in !=

null

) { in.close(); } } } }

File Write_object.java:

package

baitap_iofile.baitap3

;

import

java.io.

*;

public class

Write_object

{

public static void

main

(

String

[] args)

throws

IOException

,

ClassNotFoundException

{

int

n;

BufferedReader reader

=

new

BufferedReader(

new

InputStreamReader(

System

.in));

do

{

System

.out.print(

"Input numbers for an array: "

); n =

Integer

.parseInt(

reader

.readLine()); }

while

(n <

3

);

NhanVien nhanVien

=

new

NhanVien();

ObjectOutputStream

out =

null

;

try

{ out =

new

ObjectOutputStream(

new

BufferedOutputStream(

new

FileOutputStream(

"nhanvien.bin"

)));

for

(

int

i =

0

; i < n; i++) { out.writeObject(

nhanVien

.input() +

"

\n

"

); } }

finally

{

if

(out !=

null

) { out.close(); } } } }

File Read_object.java:

package

baitap_iofile.baitap3

;

import

java.io.BufferedInputStream

;

import

java.io.FileInputStream

;

import

java.io.IOException

;

import

java.io.ObjectInputStream

;

public class

Read_object

{

public static void

main

(

String

[] args)

throws

IOException

,

ClassNotFoundException

{

ObjectInputStream

in =

null

;

Object

nhanVien;

try

{ in =

new

ObjectInputStream(

new

BufferedInputStream(

new

FileInputStream(

"nhanvien.bin"

)));

while

((nhanVien = in.readObject()) !=

null

) {

System

.out.println(nhanVien); } }

catch

(

Exception

e) { }

finally

{

if

(in !=

null

) { in.close(); } } } }

Bài tập 4 (dựa trên bài làm của bạn Huy Tuấn)

File WordCount.java:

package

baitap_iofile.baitap4

;

import

java.io.

*;

import

java.util.Scanner

;

public class

WordCount

{

public static void

main

(

String

[] args)

throws

IOException

{

int

count =

0

;

BufferedReader reader

=

new

BufferedReader(

new

InputStreamReader(

System

.in));

String fileName

;

System

.out.print(

"Xin mời nhập vào tên của tập tin: "

);

fileName

=

reader

.readLine();

try

(

Scanner wc

=

new

Scanner(

new

FileInputStream(

fileName

))) {

while

(

wc

.hasNext()) {

wc

.next(); count++; }

System

.out.println(

"Tập tin của bạn có: "

+ count +

" từ (word)"

); } } }

File file1.txt:

Website chuyen ve lap trinh va dao tao V1Study
V1Study mang lai cho moi nguoi nhung bai hoc bo ich

Bài tập 6

package baitap6;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class baitap6 {

 public static void main(String[] args) {
   File f = new File("E:\\ttkh.txt");
   try {
       if (!f.exists()) {
           f.createNewFile();
       }
       FileWriter fw = new FileWriter(f,true); // Ghi de noi dung len file
       BufferedWriter bw = new BufferedWriter(fw);
       String data;
       Scanner nhap = new Scanner(System.in);
       System.out.println("Nhap ho ten khach hang: ");
       data = nhap.nextLine();
       System.out.println("Nhap so dien thoai khach hang: ");
       data += " " + nhap.nextLine();
       bw.write("\r\n"+data); // su dung "\r\n" de xuong dong khi ghi noi dung len file
       bw.close();  
       fw.close();
   } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
     }
 }
}

Bài tập 7

package baitap7;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystemNotFoundException;
import java.util.Scanner;
import com.sun.glass.ui.SystemClipboard;

public class baitap7 {
 public static void main(String[] args) {
    File f = new File("E:\\dtb.txt");
    String mssv;
    System.out.println("Nhap Ma So Vinh Vien: ");
    Scanner nhap = new Scanner(System.in);
    mssv=nhap.nextLine();
    try {
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);  
        String data = "";
        String dtb=""; 
        int dem=0;
        while((data = br.readLine())!=null){
            String s="";
            int dem1=0;
            for(int i=0;i<data.length();i++){
                if(data.charAt(i)==' '){
                dem1++;
                }
                if(dem1==2){
                   s+=data.charAt(i); 
                }
                if(dem1==3){
                   dem=i+1;
                   break;
                }
            }
            s=s.trim(); //loai bo khoang trang trong chuoi
            if(mssv.equals(s)==true){ 
                for(int j=dem;j<data.length();j++){
                   dtb+=data.charAt(j);
                }
                System.out.println(dtb);
                break;
            }  
       }
       if(dtb==""){
          System.out.println("Ma so ban vua nhap khong co trong ho so luu tru");
       }
    } catch(FileNotFoundException ex){
          System.out.println("file khong ton tai");
    }catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
    }
 }
}

Bài tập 9

 18.

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

public class Exercise18 {
     public static void main(String [ ] args) throws FileNotFoundException {
              new Exercise18().findLongestWords();
         }

     public String findLongestWords() throws FileNotFoundException {

       String longest_word = "";
       String current;
       Scanner sc = new Scanner(new File("/home/students/test.txt"));

       while (sc.hasNext()) {
          current = sc.next();
           if (current.length() > longest_word.length()) {
             longest_word = current;
           }

       }
         System.out.println("\n"+longest_word+"\n");
            return longest_word;
            }
}

17.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.LineNumberReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
 
public class Exercise17 {
 
    public static void main(String a[]){
        BufferedReader br = null;
        String strLine = "";
        try {
            LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream("/home/students/test.txt"), "UTF-8"));
             while (((strLine = reader.readLine()) != null) && reader.getLineNumber() <= 3){
                System.out.println(strLine);
            }
           reader.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

16.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
 
public class Exercise16 {
     public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        try
          {
             String filename= "/home/students/myfile.txt";
             FileWriter fw = new FileWriter(filename,true); 
             //appends the string to the file
             fw.write("Java Exercises\n");
             fw.close();
             BufferedReader br = new BufferedReader(new FileReader("/home/students/myfile.txt"));
             //read the file content
             while (strLine != null)
             {
                sb.append(strLine);
                sb.append(System.lineSeparator());
                strLine = br.readLine();
                System.out.println(strLine);
            }
             br.close();
           }
           catch(IOException ioe)
           {
            System.err.println("IOException: " + ioe.getMessage());
           }
        }
  }

15.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
 
public class Eexercise15 {
     public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        try
          {
             String filename= "/home/students/myfile.txt";
             FileWriter fw = new FileWriter(filename,false); 
             //appends the string to the file
             fw.write("Python Exercises\n");
             fw.close();
             BufferedReader br = new BufferedReader(new FileReader("/home/students/myfile.txt"));
             //read the file content
             while (strLine != null)
             {
                sb.append(strLine);
                sb.append(System.lineSeparator());
                strLine = br.readLine();
                System.out.println(strLine);
            }
             br.close();                          
           }
           catch(IOException ioe)
           {
            System.err.println("IOException: " + ioe.getMessage());
           }
        }
  }

14.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class Exercise14 {
 
    public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        List<String> list = new ArrayList<String>();
        try {
             BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
              while (strLine != null)
               {
                strLine = br.readLine();
                sb.append(strLine);
                sb.append(System.lineSeparator());
                strLine = br.readLine();
                if (strLine==null)
                   break;
                list.add(strLine);
            }
         System.out.println(Arrays.toString(list.toArray()));
             br.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

13.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
 
public class exercise13 {
 
    public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        String str_data = "";
        try {
             BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
             while (strLine != null)
             {
                if (strLine == null)
                  break;
                str_data += strLine;
                strLine = br.readLine();
                
            }
              System.out.println(str_data);
             br.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

12.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
 
public class Exercise12 {
 
    public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        try {
             BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
             while (strLine != null)
             {
                sb.append(strLine);
                sb.append(System.lineSeparator());
                strLine = br.readLine();
                System.out.println(strLine);
            }
             br.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

11.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
public class Exercise11 {
 
    public static void main(String a[]){
        BufferedReader br = null;
        String strLine = "";
        try {
            br = new BufferedReader( new FileReader("/home/students/test.txt"));
            while( (strLine = br.readLine()) != null){
                System.out.println(strLine);
            }
            br.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

10.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
// Reading contents from a file into byte array.
public class Exercise10 { 
  public static void main(String a[]){       
        String file_name = "/home/students/test.txt";
        InputStream fins = null;
        try {
            fins = new FileInputStream(file_name);
            byte file_content[] = new byte[2*1024];
            int read_count = 0;
            while((read_count = fins.read(file_content)) > 0){
                System.out.println(new String(file_content, 0, read_count-1));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(fins != null) fins.close();
            } catch(Exception ex){
                 
            }
        }
    }
}

9.

import java.io.File;
 
public class Exercise9 {
 
      public static void main(String[] args) 
      {
        File file = new File(“/home/students/test.txt”);
        if(file.exists())
        {
        System.out.println(filesize_in_Bytes(file));
        System.out.println(filesize_in_kiloBytes(file));
        System.out.println(filesize_in_megaBytes(file));
        }
        else 
        System.out.println(“File doesn’t exist”);
         
    }
 
    private static String filesize_in_megaBytes(File file) {
        return (double) file.length()/(1024*1024)+” mb”;
    }
 
    private static String filesize_in_kiloBytes(File file) {
        return (double) file.length()/1024+”  kb”;
    }
 
    private static String filesize_in_Bytes(File file) {
        return file.length()+” bytes”;
    }
 }

8.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

 public class Exercise8 {
  public static void main(String[] args) throws IOException
  {
    BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
    System.out.print(“Input your name: “);
    String name = R.readLine();
    System.out.println(“Your name is: ” + name);
  }
}

7.

import java.io.File;
import java.util.Date;

public class Example7 {
       public static void main(String[] args) {
       File file = new File(“test.txt”);
       Date date=new Date(file.lastModified());
       System.out.println(“\nThe file was last modified on: “+date+”\n”);       
     }
}

6.

import java.io.File;
public class Exercise6 {
   public static void main(String[] args) 
   {
       String str1 = “Java exercises”;
       String str2 = “Java exercises”;
       String str3 = “Java examples”;

       int var1 = str1.compareTo( str2 );
       System.out.println(“str1 & str2 comparison: “+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println(“str1 & str3 comparison: “+var2);

    }
}

5.

import java.io.File;
public class Exercise5 {
       public static void main(String[] args) {
        // Create a File object
        File my_file_dir = new File(“/home/students/abc.txt”);
         if (my_file_dir.isDirectory()) 
           {
            System.out.println(my_file_dir.getAbsolutePath() + ” is a directory.\n”);
           } 
         else
          {
            System.out.println(my_file_dir.getAbsolutePath() + ” is not a directory.\n”);
          }
         if (my_file_dir.isFile()) 
           {
            System.out.println(my_file_dir.getAbsolutePath() + ” is a file.\n”);
           } 
         else
          {
            System.out.println(my_file_dir.getAbsolutePath() + ” is a file.\n”);
          }  
      }
  }

4.

import java.io.File;
public class Exercise4 {
       public static void main(String[] args) {
        // Create a File object
        File my_file_dir = new File(“/home/students/abc.txt”);
         if (my_file_dir.canWrite()) 
           {
            System.out.println(my_file_dir.getAbsolutePath() + ” can write.\n”);
           } 
         else
          {
            System.out.println(my_file_dir.getAbsolutePath() + ” cannot write.\n”);
          }
         if (my_file_dir.canRead()) 
           {
            System.out.println(my_file_dir.getAbsolutePath() + ” can read.\n”);
           } 
         else
          {
            System.out.println(my_file_dir.getAbsolutePath() + ” cannot read.\n”);
          }  
      }
  }

3.

import java.io.File;
public class Exercise3 {
       public static void main(String[] args) {
        // Create a File object
        File my_file_dir = new File(“/home/students/xyz.txt”);
         if (my_file_dir.exists()) 
           {
            System.out.println(“The directory or file exists.\n”);
           } 
         else
          {
            System.out.println(“The directory or file does not exist.\n”);
          }
       }
  }

2.

import java.io.File;
import java.io.FilenameFilter;
public class Exercise2 {
       public static void main(String a[]){
        File file = new File(“/home/students/”);
           String[] list = file.list(new FilenameFilter() {
           @Override
            public boolean accept(File dir, String name) {
             if(name.toLowerCase().endsWith(“.py”)){
                    return true;
                } else {
                    return false;
                }
            }
        });
        for(String f:list){
            System.out.println(f);
        }
    }
}

1.

import java.io.File;
import java.util.Date;

public class Exercise1 {
     public static void main(String a[])
     {
        File file = new File(“/home/students/”);
        String[] fileList = file.list();
        for(String name:fileList){
            System.out.println(name);
        }
    }
}