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.
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.
I want to extract the first column in a file using the delimiter "," and save it into a new File.
Output generates this exception :
Exception in thread "main" java.lang.NullPointerException
at Extract.main(Extract.java:26)
Here is the code that I used butI am not sure if it is correct or not:
public class Extract {
public Extract(){
}
public static void main(String[] args) {
BufferedReader in = null;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));
in = new BufferedReader(new FileReader("pima.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
if (splited.length > 0)
{
out.append(splited[0].toString());
out.newLine();
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
File f = new File("prima.txt");
f.delete();
File f2 = new File("pima.tmp");
f2.renameTo(new File("pima.txt"));
}
}
Remove the first line, ie read = in.readLine();, from inside your while() loop.
The problem is that you are reading the line when you are checking the while condition and inside while loop you are reading a line again (but this time a new line, because readLine not only reads a line but also moves the reading pointer to next line) so you are getting the next line.
Once you are past the end of the file you get null instead of a line, that is why you are getting Exception.
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 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.)