I have my method all ready but it just doesn't write the duplicates to my text file as its meant to do, it prints out to screen but not to the file?
// Open the file.
File file = new File("file.txt");
Scanner inputFile = new Scanner(file);
//create a new array set Integer list
Set<Integer> set = new TreeSet<Integer>();
//add the numbers to the list
while (inputFile.hasNextInt()) {
set.add(inputFile.nextInt());
}
// transform the Set list in to an array
Integer[] numbersInteger = set.toArray(new Integer[set.size()]);
//loop that print out the array
for(int i = 0; i<numbersInteger.length;i++) {
System.out.println(numbersInteger[i]);
}
for ( int myDuplicates : set) {
System.out.print(myDuplicates+",");
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
duplicates.write(myDuplicates + System.getProperty("line.separator"));
} catch (IOException e) {
System.out.print(e);
duplicates.close();
}
//close the input stream
inputFile.close();
}
}
This part is the one im talking about
for ( int myDuplicates : set) {
System.out.print(myDuplicates+",");
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
duplicates.write(myDuplicates + System.getProperty("line.separator"));
} catch (IOException e) {
System.out.print(e);
duplicates.close();
}
//close the input stream
inputFile.close();
}
}
You're only calling duplicates.close() if there's an IOException. If you don't close the writer, you won't flush any buffered data to it. You should be closing the writer in a finally block, so that you close it whether there's an exception or not.
However, you should both open and close the file outside the loop. You want the file to be open throughout the loop. You probably want:
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
// Loop in here, writing to duplicates
} catch(IOException e) {
// Exception handling
} finally {
try {
duplicates.close();
} catch (IOException e) {
// Whatever you want
}
}
If you're using Java 7, you can do this more simply using a try-with-resources statement.
(Also, for some reason you're calling inputFile.close() in the loop, miles after you've actually finished reading from it. Again, this should be in a finally block, when you no longer need inputFile.)
Related
I am trying to write a program that takes content from one file and outputs it to another. I feel the code I wrote is really inefficient and can be improved with a loop somewhere, either when declaring variables or writing to the output file. Adding another loop is the only real concern I have. I know their are better ways to copy content from one file to another, but the way I chose works best for my understanding as being someone new to java.
public void readFile() {
//File being read
File file = new File("input.in");
try
{
Scanner scnr = new Scanner(file);
while(scnr.hasNext())
{
//Initializing/Declaring variable for each word on file input.in
String contributions = scnr.next();
String max = scnr.next();
String min = scnr.next();
String average = scnr.next();
String total = scnr.next();
try {
//output on file results.out
File outputfile = new File("results.out");
BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile));
//write each line
bw.write(contributions);
bw.newLine();
bw.write(max);
bw.newLine();
bw.write(min);
bw.newLine();
bw.write(average);
bw.newLine();
bw.write(total);
bw.close();
}
catch (IOException e) { // TODOAuto-generated
e.printStackTrace();
}
}
}
catch (FileNotFoundException e)
{ // TODO Auto-generated
e.printStackTrace();
}
}
I've been reading the book Beginning Android Games and I came across this code and text:
public static void load(FileIO files) {
BufferedReader in = null;
try { in = new BufferedReader(new InputStreamReader(
files.readFile(".mrnom")));
soundEnabled = Boolean.parseBoolean( in .readLine());
for (int i = 0; i < 5; i++) {
highscores[i] = Integer.parseInt( in .readLine());
}
} catch (IOException e) {
// :( It's ok we have defaults
} catch (NumberFormatException e) {
// :/ It's ok, defaults save our day
} finally {
try {
if ( in != null)
in .close();
} catch (IOException e) {}
}
}
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".mrnom")));
out.write(Boolean.toString(soundEnabled));
for (int i = 0; i < 5; i++) {
out.write(Integer.toString(highscores[i]));
}
} catch (IOException e) {} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {}
}
}
Next up is a method called save(). It takes the current settings and serializes them to
the .mrnom file on the external storage (e.g., /sdcard/.mrnom). The sound setting and each
high-score entry is stored as a separate line in that file, as expected by the load()
method. If something goes wrong, we just ignore the failure and use the default values
defined earlier. In an AAA title, you might want to inform the user about this loading
error
I am very confused as it says it writes to a new line(in the save method) so that in the load method, which uses readLine() works properly. However, they are only using write() with no /n characters. How will this work? Is it simply a typo?
No, it's not a typo.
BufferedReader read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. Then, it uses as delimiter the common System.lineSeparator() to split the text values.
Check the Javadoc by yourself.
My program reads in a text file, in.txt. That text file can have an arbitrary amount of lines.
My problem is that when I try to write to the output (out.txt) file, it appends it instead of overwriting.
The output file should have the same number as the input file.
try {
inFile = new Scanner(new File("in.txt"));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
finally {
outFile.flush();
outFile.close();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
The ArrayToString method returns a string to write.
EDIT:
I forgot to add this detail:
After reading the instructions again, I am not supposed to be creating a text file, just checking if it's there.
See the Javadoc for the FileWriter constructor:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Try setting the append flag to false. Then use the same writer instead of creating a new one each time through the loop (meaning that you should declare the FileWriter above the start of your while loop).
(Btw check out java.util.Arrays.toString, you shouldn't need to write your own code for this.)
The problem is here:
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
Change the PrintWriter line to:
outFile = new PrintWriter((new FileWriter("out.txt", false)));
Now, it looks like you're opening the file on every loop through your input file. If you are wanting to open this file once, and write to it for each line in the input file, move the open and close outside the while loop like this:
try {
inFile = new Scanner(new File("in.txt"));
// here we open the out file, once
outFile = new PrintWriter((new FileWriter("out.txt", false)));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
// this will write a line to the out.txt file containing the intArray as a String
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
finally {
inFile.close();
outFile.flush();
outFile.close();
}
change
outFile = new PrintWriter((new FileWriter("out.txt", true)));
to
outFile = new PrintWriter((new FileWriter("out.txt", false)));
and
outFile.println(ArrayToString(intArray));
to
outFile.print(ArrayToString(intArray));
I'm reading contents of the Spool.txt and writing it to a 77 line text file based on the codes of the first four columns.
005 means writing to Line 5
Subsequent 1 means writing to the next line
2 means writing to the next second line
3 means writing to the next third line
The issue is when I tried to write to Line 37 of the output file, it continues from the counter of the last line written. I like to write to Line 37 starting from the beginning of the file.
I'm using LineNumberReader to keep track of the number of lines I write to a text file. I understand that setLineNumber(int) does not actually not change the current position of the text file. How do I reset the counter so I can write to a specific line from the start of the file?
public static void main(String[] args) throws IOException
{
File f= new File("file1.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
Scanner sc = new Scanner(new File("Spool.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine())
{
lines.add(sc.nextLine());
}
String[] arrLine = lines.toArray(new String[0]);
//System.out.println(arrLine[1]);
for (int i=0;i<arrLine.length;i++)
{
String s1=arrLine[i].toString();
String s2= s1.substring(0,4);
if (s2.trim().equals("005"))
{
try
{
lnr.setLineNumber(4);
for(int j=1;j<=lnr.getLineNumber();j++)
bw.newLine();
bw.write(arrLine[i]);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if (s2.trim().equals("1"))
{
try
{
lnr.setLineNumber(1);
for(int j=1;j<=lnr.getLineNumber();j++)
bw.newLine();
bw.write(arrLine[i]);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if (s2.trim().equals("2"))
{
try
{
lnr.setLineNumber(2);
for(int j=1;j<=lnr.getLineNumber();j++)
bw.newLine();
bw.write(arrLine[i]);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if (s2.trim().equals("3"))
{
try
{
lnr.setLineNumber(3);
for(int j=1;j<=lnr.getLineNumber();j++)
bw.newLine();
bw.write(arrLine[i]);
}
catch (IOException e)
{
e.printStackTrace();
}
} // END Else If Loop
else if (s2.trim().equals("37")) **//ISSUE STARTS HERE: I'm trying to write to Line 37 counting from the start of the file again. It is writing to Line 37 starting from the previous lines written above**
{
try
{
lnr.setLineNumber(37);
for(int j=1;j<=lnr.getLineNumber();j++)
bw.newLine();
bw.write(arrLine[i]);
}
catch (IOException e)
{
e.printStackTrace();
}
} // END Else If Loop
}
bw.close();
lnr.close();
} //main
} //class
Indeed you can't insert into the text file. I would suggest another approach.
You open one file for reading Spool.txt and another file for writing Spool.txt.write then you read from your first file analyze each line and write to another file. Once you complete everything, just remove Spool.txt and rename Spool.txt.write to Spool.txt.
You need to access the file in a random access mode, which needs another classes to open it. And even with that, it will not allow you to insert, random access mode are well suited for replacing (and you need to control the size of each element).
A better alternative is, before writting to file, put each line in an array with the index as the line number. Once all the lines are there, iterate the array and write the lines in order.
I'm sure there is a fairly simple answer to this question, so here we go.
I'm trying to use a FileWriter to write text to a file. My program reads text in from an already existing file, specified by the user and then asks whether to print the text to the console or to a new file, also to be named by the user.
I believe my problem is with passing the FileWriter to the "FileOrConsole" method. Am I not passing or declaring the FileWriter in the "FileOrConsole" method correctly? The file is always created but nothing is written to it.
Here is the code:
import java.io.*;
import java.util.*;
public class Reader {
public static void main(String[] args) throws IOException {
Scanner s = null, input = new Scanner(System.in);
BufferedWriter out = null;
try {
System.out.println("Would you like to read from a file?");
String answer = input.nextLine();
while (answer.startsWith("y")) {
System.out.println("What file would you like to read from?");
String file = input.nextLine();
s = new Scanner(new BufferedReader(new FileReader(file)));
System.out
.println("Would you like to print file output to console or file?");
FileOrConsole(input.nextLine(), s, input, out);
System.out
.println("\nWould you like to read from the file again?");
answer = input.nextLine();
}
if (!answer.equalsIgnoreCase("yes")) {
System.out.println("Goodbye!");
}
} catch (IOException e) {
System.out.println("ERROR! File not found!");
// e.printStackTrace();
} finally {
if (s != null) {
s.close();
}
if (out != null) {
out.close();
}
}
}
public static void FileOrConsole(String response, Scanner s, Scanner input,
BufferedWriter out) {
if (response.equalsIgnoreCase("console")) {
while (s.hasNext()) {
System.out.println(s.nextLine());
}
} else if (response.equalsIgnoreCase("file")) {
System.out.println("Name of output file?");
response = input.nextLine();
try {
out = new BufferedWriter(new FileWriter(response));
} catch (IOException e) {
e.printStackTrace();
}
while (s.hasNext()) {
try {
out.write(s.nextLine());
out.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Sorry, invalid response. File or console?");
response = input.nextLine();
FileOrConsole(response, s, input, out);
}
}
}
you make classic error forgetting that parameters passed by value in case of java it is a value of the reference. The thing is that your assignment
out = new BufferedWriter(new FileWriter(response));
actually does not change the variable declared in main() it stays null
BufferedWriter out = null;
and then in finally it skips the close() by the if(out==null)
and as it is Buffered and you do no flush nothing is written to file.
what you got to do is out.close(); in side the FileOrConsole method call
OR
do the out = new BufferedWriter(new FileWriter(response));
outside of it. You choose :-)
Try flushing your stream, but more importantly, remember to close it.
Here's a code example of recommended practice for handling streams. Same approach can be used for input streams too and things like database code where it's important to always clean up after yourself to get the expected results.
BufferedWriter out = null;
try {
out = // ... create your writer
// ... use your writer
} catch(IOException ex) {
// maybe there was a problem creating or using the writer
} finally {
if (null != out) {
out.flush();
out.close();
out = null;
}
}