public static void main(String[] args) throws IOException {
InputStream istream;
int c;
final int EOF = -1;
istream = System.in;
FileWriter outFile = new FileWriter("C:/Users/boamb/Documents/NetBeansProjects/DSA_BSE20BFT/src/week7/Data.txt",true);
BufferedWriter bWriter = new BufferedWriter(outFile);
System.out.println("Enter fruits to store in data File – Press Ctrl+Z to end ");
while ((c = istream.read()) != EOF)
bWriter.write(c);
bWriter.close();
}
Hi everyone, I am trying to insert data in a file through the system output in the NETBEANS IDE but the issue is when i am pressing CTRL+Z it is not working, the program is still running and when i stop it manually there are no data saved in the file. This is my piece of code.
Actually I don't understand what is the reason for relying on EOF when your logic says "Enter fruits". I mean you should read a string, not a byte-by-byte and in this case terminator will be also some string value, "end" for example:
public static void main( String[] args ) throws IOException{
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
FileWriter outFile = new FileWriter( "C:/Users/boamb/Documents/NetBeansProjects/DSA_BSE20BFT/src/week7/Data.txt", true );
try ( BufferedWriter bWriter = new BufferedWriter( outFile ); ){
String line;
while( true ){
System.out.println( "Enter fruits to store in data File – Enter 'end' to end " );
line = br.readLine();
if( "end".equals( line ) ){
break;
}
bWriter.write( line );
bWriter.newLine();
}
bWriter.flush();
}
}
Related
Let's say I have a txt file that has the whole dictionary in it. how would I make this code be able to transer only 5-letter words into a new created txt file?
import java.io.*;
public class wordwebster {
public static void main(String[] args) throws IOException {
int five = 0;
File directory = new File(".");
String webster = directory.getCanonicalPath() + File.separator+ "webster.txt";
String fiveLetterWords = directory.getCanonicalPath()+ File.separator +"fiveLetterWords.txt";
File fin = new File(webster);
FileInputStream file = new FileInputStream(fin);
BufferedReader input = new BufferedReader(new InputStreamReader(file));
FileWriter fileStream = new FileWriter(fiveLetterWords,true);
BufferedWriter output = new BufferedWriter(fileStream);
String line = null;
while ((line = input.readLine())!= null){
output.write(line);
output.newLine();
}
input.close();
output.close();
}
}
EDIT:
As asked, let's say the input file (webster.txt) contain the words
Sentence
Frequent
Hello
Send
Variety
False
I would need only five letter words be extracted (Hello and False) and be put into a new file (fiveLetterWords.txt).
If you need to allow only words whose length is exactly five, you can just put an if condition to check before writing into file. Modify your while loop to this,
while ((line = input.readLine()) != null) {
if (line.trim().length() == 5) {
output.write(line);
output.newLine();
}
}
Hope this helps. Let me know if you face any issues.
i'm trying to read a FASTA file into a string in java.
My code works fine with small files, but when I choose a real FASTA file
which includes 5 million chars, so I can use this string, the program get stucked. get stucked= i see no output, and the program becomes with black screen.
public static String ReadFastaFile(File file) throws IOException{
String seq="";
try(Scanner scanner = new Scanner(new File(file.getPath()))) {
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine();
seq+=line;
// process line here.
}
}
return seq;
}
Try to use a StringBuilder to process big loads of text data:
public static String ReadFastaFile( File file ) throws IOException {
StringBuilder seq = new StringBuilder();
try( Scanner scanner = new Scanner( file ) ) {
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine();
seq.append( line );
// process line here.
}
}
return seq.toString();
}
I would try to use BufferedReader to read the file, something like this:
public static String readFastaFile(File file) throws IOException {
String seq="";
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process line here.
}
}
return seq;
}
And also concatenate with StringBuilder like davidbuzatto said.
If the String is found within the file in more than one place, I want to write it to file2. If that String is found in the original file OR file2, write to file3. If String was matched in any of the previous three files, write to file4.
I have used several BufferedWriters which does not work. Help here? What do I replace with "fileIAmSearching"?
import java.io.*;
import java.util.*;
public class SortGeneSym {
public static void main (String [] args) {
try {
BufferedReader br = new BufferedReader(new FileReader( "FormattedHumanRNA" ));
String line;
String genesym;
while ((line= br.readLine() ) != null)
{ String arr[] = line.split( "\t");
genesym = arr[0];
//variable genesym is the first String in line
if(fileIAmsearching.contains(genesym)) {
BufferedWriter bw1 = new BufferedWriter(new FileWriter( "1Occurance" ));
bw1.write (line);
// a match!
break;
}
else if (fileIAmSearching.contains(genesym)) {
BufferedWriter bw2 = new BufferedWriter(new FileWriter( "2Occurance"));
bw2.write (line);
break;
}
else if (fileIamSearching.contains(genesym)) {
BufferedWriter bw3 = new BufferedWriter(new FileWriter( "3Occurance"));
bw3.write (line);
break;
}
else (fileIamSearching.contains(genesym) = null ) {
BufferedWriter bw0 = new BufferedWriter(new FileWriter( "0Occurance"));
bw0.writer (line);
break;
}
}
}
catch (IOException e) {
System.out.println ("file probs dne");
}
}
}
See the API for the String class, it contains several methods that allow you to search the character values of the object. For instance, you can read each line from the file using a BufferedReader, and then search each line (String) using the contains method:
while ( ( line = br.readLine() ) != null ){
if ( line.contains(whatImSearchingFor) ){
//do something
}
}
Some other comments:
If you wish to search in a case sensitive manner, you can convert both 'needle' and 'haystack' variables to upper or lower case and then search.
If you wish to search for phrases which may overlap line breaks, you can use a StringBuilder to append each line of the File (with or without the line breaks depending on the context), then search that StringBuilder (or convert to a String)
No reason to break out of the if/else conditionals
You should close the BufferedWriters (and BufferedReaders). This is often done using a try/catch/finally, where the finally will always be called to close the Writer - you might wish to create these outside the while loop, write to them as needed, then close after the loop is complete.
I have written java code to remove initial characters from a file with 200k records , the file is removing the initial characters but its reading the file line by line and removing the characters .The program is executing very slow . Any tweaks could be made to below code to execute it faster ?
The program is executing and writing the output to a file , but its very slow
import java.io.*;
import java.util.Scanner;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
File input = new File(inputfile);
Scanner scan = new Scanner(input);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while (scan.hasNext()) {
line = scan.nextLine();
line = line.substring(number_of_char_to_erased);
print.println(line);
}
scan.close();
print.close();
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
What appears to be the issue here is that you just created a buffered reader to read the file. Then, it reads the first line of the file. Then, you create a Scanner to read ALL the lines in the file, omitting certain characters. Then your BufferedReader reads the next line in the file. And the process repeats itself. So all you have to do is this:
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
print.println(line.substring(number_of_char_to_erased);
}
print.close();
This should much faster. Basically, since you've already allocated line to the read line from the file, you can simply print out that line, minus the number of chars, to the output file. The entire for loop with scanner was entirely unnecessary, and closing and opening the print stream for each line was also unnecessary.
EDIT: Removed the println statement since it would slow it down a bit.
Try this (Scanner and Println removed, output file refactored outside the loop):
import java.io.*;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
String trimmedLine = line.substring(number_of_char_to_erased);
print.println(trimmedLine);
}
// Always close files.
bufferedReader.close();
print.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
Am having the below code , creating a Temp file and read that and deleting the file.
But after deletion also file available to read .Please help to find wrong with my code....
public static void main(String args[]) throws Exception
{
Calendar mSec = Calendar.getInstance();
String fileName="hubname_"+"msgname_"+mSec.getTimeInMillis();
String str ="Hello How are you doing .......";
System.out.println("fileName :"+fileName);
File f = File.createTempFile(fileName, ".xml");
FileWriter fw = new FileWriter(f);
fw.write(str);
fw.flush();
fw.close();
printFileContent(f);
f.delete();
printFileContent(f);
}
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
}
Output :
fileName :hubname_msgname_1358655424194
stringBuilder.toString() :Hello How are you doing .......
stringBuilder.toString() :Hello How are you doing .......
You should close reader in printFileContent. File.delete cannot delete an opened file (at least on Windows, see Keith Randall's comment below) in which case it returns false. You could check if delete was successful
if (!f.delete()) {
throw new IOException("Cannot delete " + f);
}
The following comment was added to File.delete API in Java 7
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
if(reader != null){
reader.close();
}
}