简体   繁体   中英

Why doesn't printwriter actually write to the file?

I've been struggling with this problem for a couple of hours now and am not sure how best to proceed.

The code should read a file in encode it using the caesar cipher, writing it to disk to a new file with _encoded appended to it.

It certainly creates the file but it is blank everytime. When I look at the docs, it says to make sure to flush and close the printwriter. I've done that.

I also thought it was perhaps because I was approaching the problem in a roundabout way; I wondered if it was the use of a FileOutputstream.

        Scanner sc=new Scanner(inFile);
        //File outFile=new File("caesar_encoded.txt");

        //FileOutputStream outFileStream=new FileOutputStream(outFile);
        PrintWriter outStream=new PrintWriter("caesar_encoded.txt");

        while(sc.hasNext())
        {
            String phrase = sc.nextLine().toUpperCase();
    for (int i = 0; i < phrase.length(); i++) {
        if (Character.isLetter(phrase.charAt(i))) {
            for (int j = 0; j < alpha.length; j++) {
                if (phrase.charAt(i) == alpha[j]) {
                    if (j == alpha.length - 1) {
                        outStream.print(alpha[0]);
                    } else {
                        outStream.print(alpha[j + 1]);
                    }
                }
            }
        } else {
            outStream.print(phrase.charAt(i));
        }
    }
    outStream.println();
        }
        outStream.flush();
        outStream.close();

        sc.close();

I tried doing this but with the same result:

Scanner sc=new Scanner(inFile);
 File outFile=new File("caesar_encoded.txt");
 FileOutputStream outFileStream=new FileOutputStream(outFile);
 PrintWriter outStream=new PrintWriter(outFileStream);

Decorate it:

PrintWriter pw = new PrintWriter(new FileWriter("caesar_encoded.txt"), true);

Or this:

PrintStream ps = new PrintStream(new FileOutputStream("caesar_encoded.txt"), true);

Of course you understand the difference between Writer (character streams) and OutputStream (byte streams) hierarchies. You don't normally cross the two. You can jump from OutputStream to Writer with OutputStreamWriter , but you can't go the other way.

This code runs perfectly for me. I took your method at its word, guessing about the SHIFTED array. In any case, I get output in the encrypted.txt file. I think it's your scanner that's the problem.

package io;

import java.io.*;

/**
 * PrintWriterDemo
 * @author Michael
 * @link http://stackoverflow.com/questions/12849855/why-doesnt-printwriter-actually-write-to-the-file/12849867#comment17389040_12849867
 * @link http://en.wikipedia.org/wiki/Caesar_cipher
 * @since 10/11/12 7:17 PM
 */
public class PrintWriterDemo {

    public static void main(String[] args) {
        try {
            File unencrypted = new File((args.length > 0) ? args[0] : "resources/unencrypted.txt");
            File encrypted = new File((args.length > 1) ? args[1] : "resources/encrypted.txt");
            caesar(unencrypted, encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final char [] SHIFTED = { 
            'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C' };

    public static void caesar(File unencrypted, File encrypted) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(unencrypted));
        PrintWriter pw = new PrintWriter(encrypted);
        String line = "";
        while ((line = br.readLine()) != null) {
            String phrase =line.toUpperCase();
            for (int i = 0; i < phrase.length(); i++) {
                if (Character.isLetter(phrase.charAt(i))) {
                    for (int j = 0; j < SHIFTED.length; j++) {
                        if (phrase.charAt(i) == SHIFTED[j]) {
                            if (j == SHIFTED.length-1) {
                                pw.print(SHIFTED[0]);
                            } else {
                                pw.print(SHIFTED[j+1]);
                            }
                        }
                    }
                } else {
                    pw.print(phrase.charAt(i));
                }
            }
            pw.println();
        }
        pw.flush();
        pw.close();
        br.close();
    }
}

Here's my unencrypted.txt input:

This should work out fine.
I have no idea what the problem is with the original code.
But I do know that this writes just fine.

And here's my encrypted.txt output:

UIJT TIPVME XPSL PVU GJOF.
J IBWF OP JEFB XIBU UIF QSPCMFN JT XJUI UIF PSJHJOBM DPEF.
CVU J EP LOPX UIBU UIJT XSJUFT KVTU GJOF.

Your code worked fine for me. I've pasted my changes which do not affect the functionality. Perhaps you haven't initialized char[] alpha correctly (not in the code you posted) or need to use the full file names like I did.

File inFile = new File("C:\\Users\\name\\Documents\\workspace\\Testing\\src\\receiver.txt");
Scanner sc=new Scanner(inFile);//unchanged
char[] alpha =  {'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'}; 
PrintWriter outStream=new PrintWriter("C:\\Users\\name\\Documents\\workspace\\Testing\\src\\caesar.txt");
//rest of code is identical
/*
receiver.txt (input file):
<?xml version="1.0" encoding="UTF-8"?>
<tradeevent>
   <event>
      <eventId>612</eventId>
      <relatedId>0</relatedId>
      <operationalEventIndicator></operationalEventIndicator>
      <effectiveDate>2012-08-07T11:20:47.09</effectiveDate>
      <id>612</id>
      <createdOnDate>0</createdOnDate>
   </event>
   <trade>
...
caesar.txt (created output file):
<? FJ="1.0" FDEJH="G-8"?>
<EFFF>
   <FF>
      <FFJE>612</FFJE>
      <FFEJE>0</FFEJE>
      <FJFFJEJD></FJFFJEJD>
      <FGGFDJFEF>2012-08-0711:20:47.09</FGGFDJFEF>
      <JE>612</JE>
      <DFFEEF>0</DFFEEF>
   </FF>
   <EF>
...
*/

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