các bác giúp em mới - e ko biết cho hàm này zô main thế nào

tình hình là cái này là bài tập do thầy đưa ra mà em hơi dốt nên đi copy ạ. nên ko biết cho hàm kia zô main thế nào, các bác giúp em với . em cám ơn ạ

package bai3;

import java.io.DataOutputStream;
import java.io.File;
import static java.io.FileDescriptor.out;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

/**
*

  • @author Tuan Phung
    */
    public class Bai3 {

    /**

    • @param args the command line arguments
      */
      public static void main(String[] args) throws FileNotFoundException {
      DataOutputStream x;
      ///////

    }

    DataOutputStream dos;
    public boolean writeTOFile(String fileName, String dataLine,
    boolean isAppendMode, boolean isNewLine){
    if(isNewLine){
    dataLine = “\n” + dataLine;
    }
    try{
    File outFile = new File(fileName);
    if (isAppendMode){
    dos = new DataOutputStream(new FileOutputStream(fileName, true));

         }//end iff
         else{
             dos = new DataOutputStream(new FileOutputStream(outFile));            
         }// end else
         dos.writeBytes(dataLine);
         dos.close();   
     }
     catch (FileNotFoundException ex){
         return (false);
     }catch (IOException ex){
         return (false);
     }
     return (true);
    

    }

}

Bạn đổi chữ kí method thành public static boolean writeTOFile(String fileName, String dataLine, boolean isAppendMode, boolean isNewLine). Vì method main là method static nên nó chỉ gọi được các method static thôi

ý em là em ko biết trong main viết gì để ra đó bác. các này là :Làm việc với file văn bản (txt): Ghi nội dung ra file văn bản.

Trước tiên thì mình nói qua cái tham số của method writeTOFile đã:

  1. fileName : tên (đường dẫn) tới file cần ghi.
  2. dataLine : dữ liệu cần ghi vào file
    3.isAppendMode : chế độ ghi (true - ghi tiếp vào file, false - tạo mới rồi ghi vào file)
  3. isNewLine: có xuống dòng hay không ( true - có, false - không)

Theo như code ở trên thì trong hàm main sẽ như sau:
Ví dụ mình muốn ghi nội dung “abcxyz” vào file có tên “input.txt” và cùng thư mục với class Bai3

public static void main(String[] args) throws FileNotFoundException {
 Bai3 o = new Bai3();
 o.writeTOFile("input.txt", "abcxyz", true, true);
}

Lần sau đừng copy nhé :wink:

2 Likes

vâng em cám ơn ! sâu mắt

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?