Output not printing to txt file Java - java

I am trying to create a program which prints out all the possible combinations of the letters "AUGC".
The output would really print to a txt file and the result would be a txt file with something like this:
"AAA
AAG
AAC
AAU
AGA"
etc
Here is the code I have so far:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Permute {
static String s = "ACGU";
static void permute(int level, String prefix) {
if (level == 0) {
String fileName = "out.txt";
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(fileName);
outputStream.println(prefix);
System.out.println(prefix);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < s.length(); i++) {
permute(level - 1, prefix + s.charAt(i));
}
}
public static void main(String[] args) {
int k = 2;
permute(k, "");
}
}
Currently the program is printing all the output to the console and only the last permutation to the txt file.
I would like it to print all the information to both.
Any help would be greatly appreciated

You are closing OutputStream prematurely. Since you are using recursion, pass OutputStream as a parameter to permute method from main method. Initialize stream and close it in main method.

I maybe wrong on this one but do you not need to include a "\n" as part of your outputStream.println(prefix);
so that is looks like
outputStream.println(prefix + "\n");
This will help as it seems to replacing the line with the newest details and not on a new line which is what you seem to be looking for.

Related

JAVA String Reversing order of string in file io

I have to write code that will reverse the order of the string and write it in a new file. For example :
Hi my name is Bob.
I am ten years old.
The reversed will be :
I am ten years old.
Hi my name is Bob.
This is what I have so far. Not sure what to write for the outWriter print statement. Any help will be appreciated. Thanks!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class FileRewinder {
public static void main(String[] args) {
File inputFile = new File("ascii.txt");
ArrayList<String> list1 = new ArrayList<String>();
Scanner inputScanner;
try {
inputScanner = new Scanner(inputFile);
} catch (FileNotFoundException f) {
System.out.println("File not found :" + f);
return;
}
while (inputScanner.hasNextLine()) {
String curLine = inputScanner .nextLine();
System.out.println(curLine );
}
inputScanner.close();
File outputFile = new File("hi.txt");
PrintWriter outWriter = null;
try {
outWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
System.out.println("File not found :" + e);
return;
}
outWriter.println(???);
outWriter.close();
}
}
My suggestion is read entire file first and store sentences(you can split by .) in a LinkedList<String>(this will keep insertion order)
Then use Iterator and get sentences in reverse order. and write them into a file. make sure to put . just after each sentence.
After System.out.println(curLine ); add list1.add(curline); that will place your lines of text into your list.
At the end create a loop over list1 backwards:
for(int i = list1.size() - 1 , i > 0, --i) {
outWriter.println(list1[i]);
}
If the file contains an amount of lines which can be loaded into the memory. You can read all lines into a list, reverse the order of the list and write the list back to the disk.
public class Reverse {
static final Charset FILE_ENCODING = StandardCharsets.UTF_8;
public static void main(String[] args) throws IOException {
List<String> inLines = Files.readAllLines(Paths.get("ascii.txt"), FILE_ENCODING);
Collections.reverse(inLines);
Files.write(Paths.get("hi.txt"), inLines, FILE_ENCODING);
}
}

How can I parse through a file for a string matching a generated string?

My bad for the title, I am usually not good at making those.
I have a programme that will generate all permutations of an inputted word and that is supposed to check to see if those are words (checks dictionary), and output the ones that are. Really I just need the last the part and I can not figure out how to parse through a file.
I took out what was there (now displaying the "String words =") because it really made thing worse (was an if statement). Right now, all it will do is output all permutations.
Edit: I should add that the try/catch was added in when I tried turning the file in a list (as opposed to the string format which it is currently in). So right now it does nothing.
One more thing: is it possible (well how, really) to get the permutations to display permutations with lesser characters than entered ? Sorry for the bad wording, like if I enter five characters, show all five character permutations, and four, and three, and two, and one.
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Permutations
{
public static void main(String[] args) throws Exception
{
out.println("Enter anything to get permutations: ");
Scanner scan = new Scanner(System.in);
String io = scan.nextLine();
String str = io;
StringBuffer strBuf = new StringBuffer(str);
mutate(strBuf,str.length());
}
private static void mutate(StringBuffer str, int index)
{
try
{
String words = FileUtils.readFileToString(new File("wordsEn.txt"));
if(index <= 0)
{
out.println(str);
}
else
{
mutate(str, index - 1);
int currLoc = str.length()-index;
for (int i = currLoc + 1; i < str.length(); i++)
{
change(str, currLoc, i);
mutate(str, index - 1);
change(str, i, currLoc);
}
}
}
catch(IOException e)
{
out.println("Your search found no results");
}
}
private static void change(StringBuffer str, int loc1, int loc2)
{
char t1 = str.charAt(loc1);
str.setCharAt(loc1, str.charAt(loc2));
str.setCharAt(loc2, t1);
}
}
If each word in your file is actually on a different line, maybe you can try this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null)
{
... // check and print here
}
Or if you want to try something else, the Apache Commons IO library has something called LineIterator.
An Iterator over the lines in a Reader.
LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}

Infinite loop during file reading and String.split() not working properly

I have a text file admin.dat which looks like this:
blackranger|sdasdasdasd23123|1000
blueranger|sdasdasdasdwhhh22|1000
brownranger|lppsadospd123|1000
I am trying to read every line, using | as my delimiter and outputting to the console every section.
Code:
package testing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner filereader = null;
try {
filereader = new Scanner(new File("./src/testing/players.dat"));
String data;
while(filereader.hasNextLine()) {
String foo = "abc|123|a213";
String[] bar = foo.split("|");
for (int i = 0; i < 3; i++) {
System.out.println(bar[i]);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error while reading file");
} finally {
if (filereader != null) {
filereader.close();
}
}
}
}
Expected Outcome:
blackranger
sdasdasdasd23123
1000
blueranger
sdasdasdasdwhhh22
1000
brownranger
lppsadosph123
1000
Actual Outcome:
a // infinite loop
b
a
b
a
b
a
b
a
b
Why am I getting an infinite loop which prints a b forever?
You should escape the character | because it has special meaning in regex
foo.split("\\|");
But firstly, assign foo with value that you read from the file, not by hard-coded it:
String foo = filereader.nextLine();
You never read from the fileReader inside the while loop, so while(filereader.hasNextLine()) will always be true, and it makes sense that the loop will never end. What surprised me is that it looked like you had code that did read from the fileReader inside of the loop but commented it out. Why?
Solution: don't do this. Make sure to change the test condition inside the while loop, else the while loop will never end.
String foo = filereader.nextLine();
String[] bar = foo.split("\\|");
instead of
String foo = "abc|123|a213";
String[] bar = foo.split("|");

Java File .write() a stream of integers

I run this code, I get "File written !" and when I open the file to see it, every thing that is written is not making any sense. You can understand that I want to write 012345678910 in the file. Is there any other way to write in file than buffW.write(k);. Are there any other mistakes I made?
package thema4_create_write_read_file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FW {
public static void main(String[] args) {
File newFile = new File("newFile.txt");
if (newFile.exists()) {
System.out.println("The file already exists");
} else {
try {
newFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileWriter fileW = new FileWriter(newFile);
BufferedWriter buffW = new BufferedWriter(fileW);
for (int k = 0; k <= 10; k++) {
buffW.write(k); // This is where the problem occurs
}
buffW.close();
System.out.print("File written !");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Is there any way of writing (k) as integer and not as string ,in order to read it as int then?
Bufferedwriter#write(int c):
Writes a single character.
Parameters:
c - int specifying a character to be written
Use Writer#write(String)
writer.write(String.valueOf(integer));
BufferedWriter#write(int i) writes character that corresponds to i in Unicode Table you can take a look what will be written by using
System.out.print((char)k);
Now if you want to write int value of k you should probably use PrintWriter
PrintWriter printW = new PrintWriter(fileW);
printW.print(k);
You can also take a look at PrintStream#print() method (System.out is instance of PrintStream) but Writers are preferred over Streams for character I/O operations.

Not able to see output

import java.io.FileInputStream;
import org.apache.commons.codec.binary.Base64;
public class Encode
{
public static String encodeFileStream(String filePath) throws Exception //file path ex : C:\Program Files\Cordys\Web\reports\I0001180.pdf
{
StringBuffer sb=new StringBuffer();
try
{
FileInputStream fin = new FileInputStream(filePath);
//StringBuffer sb=new StringBuffer();
int lineLength = 72;
byte[] buf = new byte[lineLength/4*3];
while (true)
{
int len = fin.read(buf);
if (len <= 0)
{
break;
}
//new Base64().encode(byte);
//sb.append(Base64.encode(buf));
//sb.append(Base64.encodeBase64(buf));
Base64 b = new Base64();
sb.append(b.encode(buf));
//return sb.toString();
}
}
catch(Exception e)
{
return e.getMessage();
}
return sb.toString();
}
public static void main(String args[]) throws Exception
{
try
{
String s="";
s=encodeFileStream("E:/CSSDocument/Test.pdf");
}
catch(Exception e)
{
e.getMessage();
}
}
}
after the line
s=encodeFileStream("E:/CSSDocument/Test.pdf");
add
System.out.println(s);
and please clean your code :)
One reason that you cannot see any output is that your program doesn't write any output. The main method calls encodeFileStream to read and encode the file, assigns the result to the String variable s ... and then exits without outputting it.
Add System.out.println(s); (or something like that) to output the encoded file contents.
Other points:
Your code is a mess. Fix the whitespace and indentation.
The method encodeFileStream is poorly named. What it is doing is encoding a file's contents ... not the contents of a "file stream".
Your buffer length is probably too small ... and PDF files are binary so the notion of a "line length" is meaningless.
Hard-wiring a pathname into your code is ... probably not what is required.
Your program will encode the last "buffer" of the file incorrectly (most of the time). Hint: len can be values other than 0 and buf.length.

Categories