How can I write it to a text file in Java? [closed]

EDIT: I fixed it with your help with PrintWriter.

So, I have this program, or this loop from the program. It reads data from a file, and then prints YES if ok = true, NO if ok = false. The output to the console works, prints:

NO
YES

But I need it to print it the same way to a text file. Tried using BufferedReader, but then it only prints

YES
for (int j = 0; j < m; j++)
{
    str = s.nextLine();
    String[] pair = str.split("\\s+");
    int x = Integer.parseInt(pair[0]);
    int y = Integer.parseInt(pair[1]);
    System.out.printf("Switching cards: %d %d\n",x,y);
    x--;
    y--;
    Pair tempPair = P[x];
    P[x] = P[y];
    P[y] = tempPair;
    int p = -infty;
    boolean ok = true;
    for (int i = 0; i < n; i++)
    {
        if (P[i].first >= p)
        {
                p = P[i].first;
        }
        else if (P[i].second >= p)
        {
                p = P[i].second;
        }
        else
        {
                ok = false;
                break;
        }
    }
   
    System.out.println(ok ? "YES\n" : "NO\n");
}

i modify your code try this.

BufferedWriter output = null;
        try {    
        File file = new File("example.txt");
        output = new BufferedWriter(new FileWriter(file));
        for (int j = 0; j < m; j++) {
                str = s.nextLine();
                String[] pair = str.split("\\s+");
                int x = Integer.parseInt(pair[0]);
                int y = Integer.parseInt(pair[1]);
                System.out.printf("Switching cards: %d %d\n", x, y);
                x--;
                y--;
                Pair tempPair = P[x];
                P[x] = P[y];
                P[y] = tempPair;
                int p = -infty;
                boolean ok = true;
                for (int i = 0; i < n; i++) {
                    if (P[i].first >= p) {
                        p = P[i].first;
                    } else if (P[i].second >= p) {
                        p = P[i].second;
                    } else {
                        ok = false;
                        break;
                    }
                }
            
                System.out.println(ok ? "YES\n" : "NO\n");
                output.write(ok ? "YES\n" : "NO\n");
            }
        } 
    catch ( IOException e ) {
                    e.printStackTrace();
                } 
    finally {
                  if ( output != null ) {
                    output.close();
                  }