Weird File Output behavior in java

Click For Summary
SUMMARY

The discussion centers on a Java implementation of RSA encryption that encounters issues with file output when reading from standard input. The user reports that while the program works correctly with an input file, it fails to write output files when using standard input. The solution identified involves calling the flush() method on the BufferedWriter to ensure that data is written to the file. This issue appears to be specific to the environment, as the program operates correctly in Eclipse but not on a Linux server.

PREREQUISITES
  • Java programming knowledge, particularly with I/O operations
  • Understanding of RSA encryption and its implementation
  • Familiarity with the Java BufferedWriter class
  • Basic knowledge of command-line argument handling in Java
NEXT STEPS
  • Research the Java BufferedWriter class and its flush() method
  • Explore Java I/O best practices for file handling
  • Learn about debugging file I/O issues in different environments
  • Investigate the differences in Java execution between IDEs like Eclipse and command-line interfaces
USEFUL FOR

Java developers, students learning about encryption, and anyone troubleshooting file I/O issues in Java applications.

nhartung
Messages
56
Reaction score
0

Homework Statement


I've implemented RSA and just need to print some stats and write to files.

Homework Equations


My solution works fine when I provide an input file, however, if I let it read from standard input there is no output written to either of my output files. Reading works regardless. I really have no idea what is going on here. I'm not really familiar with java IO so i figure I must be doing something wrong here.

The Attempt at a Solution



Code:
public static void main(String args[]) {
		String message = new String();
		String outFile = "out.txt"; // Default output file.
		// If no arguments are provided then standard input is used to collect input.
		if(args.length == 0) {
			System.out.println("No input file provided, using standard input: ");
			Scanner stdIn = new Scanner(System.in);
			message = stdIn.nextLine();
		}
		// If one or 2 arguments are provided the first is assumed to be an input text file.
		if(args.length == 1 || args.length == 2) {
			FileInputStream fin;		
			String line;
			try {
				// Opening file
				System.out.println("Opening file " + args[0] + " ...");
			    fin = new FileInputStream (args[0]);
			    BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
			    line = reader.readLine();
			    System.out.println("Reading from file... ");
			    // Getting data from file
			    while(line != null) {
			    	message += line;
			    	line = reader.readLine();
			    }
			    // Closing file
			    fin.close();
			}
			// Unable to read file, using Standard Input instead.
			catch (IOException e) {
				System.err.println ("Unable to read from file, \"" + args[0] + "\" , using standard input instead: ");
				Scanner stdIn = new Scanner(System.in);
				message = stdIn.nextLine();
			}
		}
		// The second parameter is assumed to be an output text file to store the cipherText output.
		if(args.length == 2) {
			outFile = args[1];
		}
		// Invalid usage, exiting.
		if(args.length > 2) {
			System.out.println("Too many arguments. Usage: RSA [inputFilename] [outputFilename]\nEnd.");
			return;
		}
		// Init RSA
		SecureRandom random = new SecureRandom();
		RSA test = new RSA(NBITS, NBITS, random);
		System.out.println("Checking if computed RSA values are secure...");
		// Check is RSA values are secure
		if(test.isSecure()) {
			System.out.println("RSA values are secure continuing with Encryption...");
			System.out.println("Encrypting " + message.length() + " bytes of data...");
			long startEncrypt = System.currentTimeMillis();
			// Encrypt message
			BigInteger[] out = test.encryptString(message);
			long endEncrypt = System.currentTimeMillis();
			System.out.println("Encryption completed in " + (endEncrypt - startEncrypt) + " ms.");
			//Write CipherText to file.
			try {
				FileWriter fout;	
				// Opening file
				System.out.println("Opening file \"" + outFile + "\" ...");
			    fout = new FileWriter(outFile);
			    BufferedWriter writer = new BufferedWriter(fout);
			    
			    System.out.println("Writing ciphertext to file = \"" + outFile + "\".");
			    // Parsing through ciphertext blocks
			    for(int i = 0; i < out.length; i++) {
			    	//System.out.println("Writing: " + out[i].toString());
			    	writer.write(out[i].toString());
			    }
			    // Closing file
			    fout.close();	
			    System.out.println("Finished writing to \"" + outFile + "\".");
			}
			// Error opening output file
			catch (IOException e) {
				System.err.println ("Unable to open file \"" + outFile  + "\"Ciphertext will not be written.");
			}
			System.out.println("Decrypting " + message.length() + " bytes of data...");
			long startDecrypt = System.currentTimeMillis();
			// Decrypt message
			String plainText = test.decryptString(out);
			long endDecrypt = System.currentTimeMillis();
			System.out.println("Decryption completed in " + (endDecrypt - startDecrypt) + " ms.");
			// Write plainText to file
			try {
				FileWriter foutf;	
				// Opening file
				System.out.println("Opening file \"" + "plainTextOut.txt" + "\" to ensure encyption/decryption occurred without error.");
			    foutf = new FileWriter("plainTextOut.txt");
			    BufferedWriter writer = new BufferedWriter(foutf);
			    
			    System.out.println("Writing plainText to file \"" + "plainTextOut.txt" + "\".");
			    // Write plaintext to file.
			    //System.out.println("Writing: " + plainText);
			    writer.write(plainText);
			    // Closing file
			    foutf.close();	
			    System.out.println("Finished writing to \"" + "plainTextOut.txt" + "\".");
			}
			// Error opening output file
			catch (IOException e) {
				System.err.println ("Unable to open file \"" + "plaintTextOut.txt."  + "\"Plaintext will not be written.");
			}
		}
		else
			System.out.println("RSA values are not secure, please try again.");
	}

Probably worth noting that output to files only works on Eclipse. When I tried to run it on my schools linux server output doesn't work even if I provide it an input file..
 
Last edited:
Physics news on Phys.org
Nevermind. I resolved this issue. Apparently you need to call the BufferedWriter's flush() member. Strange that it was working in certain scenarios though.
 

Similar threads

  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 8 ·
Replies
8
Views
10K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 10 ·
Replies
10
Views
11K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K