read from one file, modify and output to another file in java - java

The assignment is to read a file, create a new file that matches the input file but has numbers lines added
I have several examples to copy from. I have tried new File(), new FileReader() and BufferedReader(). I can't seem to get any data out of the input file
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Hw1_43 {
public static void main(String[] args) throws FileNotFoundException
{
// Prompt user for input file name
Scanner in = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFileName = in.next(); // instantiate input file name for later use
Scanner inputFile = new Scanner(new FileReader(inputFileName));
//ArrayList<String> line = new ArrayList();
int counter = 0;
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(counter + line);
counter ++;
}
System.out.println(inputFileName);
}
}
Also after I get the input file to read and write it into an output file, where is the output file so I can look at it to make sure it is correct?

FileReader only reads from a file. You need to create a FileWriter, which writes to a file (e.g. FileWriter outputFile = new FileWriter ("C:/tmp/output_file.txt")). As you read from the FileWriter, prepend the line numbers to each line, then write to the FileWriter.
I recommend using BufferedReader instead of Scanner. You can then use then uses the .readLine() or .lines() methods, the latter can be streamed into a BufferedWriter.

Related

Append text to the beginning of every line in a file

Please note, this is a homework assignment.
Can anybody help me figure out how to append text to the beginning of every line of a text file? This is what I have so far:
package addStr;
import java.util.*;
import java.io.*;
public class AddStr {
public static void main(String args[]) throws FileNotFoundException, IOException{
Scanner con = new Scanner(System.in);
System.out.print("Enter input file: ");
String fileIn = con.next();
System.out.print("Enter output file: ");
String fileOut = con.next();
File in = new File(fileIn);
Scanner sc = new Scanner(in);
FileWriter out = new FileWriter(in, true);
PrintWriter print = new PrintWriter(out);
print.print("hello");
print.close();
}
}
I only printed "hello" as a test to see where in the file it would append. It appends at the end of the very last line. I need it to append to the beginning of the first line, and then use a loop to append it to the beginning of each subsequent line.
Also, the program prompts the user to input the file name.
The simplest way to change the content of a file is to open it for reading, read it into a structure, re-open the file for writing then write from the structure back to file. Unless the file is large then the performance will be perfectly acceptable.
If you are using Java 8 then this can be quite trivial. Assuming you have a Path to the file:
List<String> lines = Files.lines(path).map(s -> "Prefix" + s).collect(Collectors.toList());
Files.write(path, lines);

Another java.io.FileNotFoundException (The system cannot find the file specified) thread

I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".

How to display text written to an external text file on Java?

I was wondering because I made my program save data to an external program, but I need to know how to display on Java.
Here's the code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StoringInfo {
public static void main(String[] args) throws IOException {
Scanner keyboard=new Scanner(System.in);
System.out.print("\n Enter the customer's name: ");
String name1=keyboard.next();
System.out.print("\n Enter the customer's first part of the address: ");
String Address=keyboard.next();
System.out.print("\n Enter the rest of the address:");
String Address2=keyboard.next();
System.out.print("\n Enter the customer's E-mail: ");
String Email=keyboard.next();
System.out.print("Customer has been added to the list.");
File file = new File("CustomerData.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.println(name1);
output.println(Address);
output.println(Address2);
output.println(Email);
I was wondering if you use something like BufferedReader or another code?
output.close();
You can use a Scanner to read from files too.
File file = new File("CustomerData.txt");
Scanner fileReader = new Scanner(file);
And you can apply the knowledge you know about Scanners to this.
Alternatively you could use a BufferedReader (which is faster).
BufferedReader reader = new BufferedReader(new FileReader("CustomerData.txt"));
And use:
reader.readLine();
To read the next line.

why is Scanner's hasNext() method initially returning false for a non-empty text file?

I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.

Modify or Delete Data in a File

Today I was trying the algorithm for modifying and deleting data inside a file using Java in Windows platform.
1st : create a temporaryFile
2nd : write the data you wanted inside the originalFile into a String and to the temporaryFile
3rd : rename temporaryFile to originalFile.
The Code:
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class testing{
private static String temp;
public static void main(String [] args)
{
try{
File tempFile = File.createTempFile("haha\\temporary", ".txt"); //create a temporary file in haha folder
FileWriter writer = new FileWriter(tempFile);
Scanner input = new Scanner(new File("haha\\testing.txt")); //get input from testing.txt
temp = input.next();
writer.write(temp);
writer.close();
File origFile = new File("haha\\testing.txt");
tempFile.renameTo(origFile);
}
catch ( FileNotFoundException fileNotFoundException ){}
catch(IOException ioException){}
}
}
In the above code , the textFile to be edited is located inside a folder name haha which is located inside another folder together with the testing.class.I've tried this code to no avail , the originalTextFile has no changes .
If you have your file in the same directory, you don't need to pass the path to the File constructor.
Scanner input = new Scanner(new File("testing.txt"));
This should do it.
You need to close the Scanner object to make the changes, the underlying operating system has a file lock that must be released.
input.close();
File origFile = new File("haha\\testing.txt");

Categories

Resources