Weird File Output behavior in java

In summary, the conversation was about a person's implementation of RSA and their difficulty in printing stats and writing to files. They found that their solution worked when provided with an input file, but not when reading from standard input. They were unsure of the issue and mentioned being unfamiliar with Java IO. The person shared their code, which included checks for input files, opening and reading from files, and writing to output files. The conversation also mentioned issues with output not working on a school's Linux server, but the problem was later resolved by calling the BufferedWriter's flush() member.
  • #1
nhartung
56
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
  • #2
Nevermind. I resolved this issue. Apparently you need to call the BufferedWriter's flush() member. Strange that it was working in certain scenarios though.
 

Related to Weird File Output behavior in java

1. What is "Weird File Output behavior" in Java?

"Weird File Output behavior" refers to any unexpected or unusual results that occur when writing to or reading from a file using Java. It may include errors, missing data, or other anomalies that do not align with the expected output.

2. What are some possible causes of Weird File Output behavior in Java?

There are several potential causes for this behavior, including incorrect code implementation, file permissions, file encoding issues, or file corruption. It could also be caused by external factors such as hardware or system failures.

3. How can I troubleshoot Weird File Output behavior in Java?

First, check for any errors or warnings in your code. Then, ensure that the file is being accessed correctly and with the proper permissions. You can also try using different file encoding methods or checking for any hardware or system issues. Additionally, you can use debugging tools or consult online resources for further assistance.

4. How can I prevent Weird File Output behavior in Java?

To prevent Weird File Output behavior, make sure to thoroughly test your code before running it in a production environment. Double-check for any errors or warnings and ensure that your code is properly handling file operations. It is also important to properly close files after use and handle any potential exceptions that may arise.

5. Are there any best practices for dealing with file output in Java?

Yes, there are several best practices for handling file output in Java. These include properly closing files after use, using try-catch blocks to handle exceptions, using relevant file handling classes and methods, and using appropriate file encoding methods. It is also important to regularly test and troubleshoot your code to prevent any potential issues with file output.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
2K
  • Programming and Computer Science
Replies
3
Views
803
  • Engineering and Comp Sci Homework Help
Replies
8
Views
9K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
10K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
4K
  • Programming and Computer Science
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
3K
Back
Top