Java: Copy textfile content to another without replacing - java

I want to take the content of one text file chosen by the user and add it to another text file without replacing the current content. So for example:
Update: How do I add it to the second file in a numbered way?
TextFile1:
AAA BBB CCC
AAA BBB CCC
TextFile2: (After copying)
EEE FFF GGG
AAA BBB CCC
AAA BBB CCC
Update: I had to remove my code as it may be taken for plagiarism, This was answered so I know what to do, thanks for everyone helping me out.

Try this
You have to use
new FileWriter(fileName,append);
This opens the file in append mode:
According to the javadoc it says
Parameters:
fileName String The system-dependent filename.
append boolean if true, then data will be written to the end of the file rather than the beginning.
public static void main(String[] args) {
FileReader Read = null;
FileWriter Import = null;
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Read = new FileReader(filename);
Import = new FileWriter("songstuff.txt",true);
int Rip = Read.read();
while(Rip!=-1) {
Import.write(Rip);
Rip = Read.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(Read);
close(Import);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
// JavaProgram();
}
}

Use new FileWriter("songstuff.txt", true); to append to the file instead of overwriting it.
Refer : FileWriter

You can use Apache commons IO.
Apache Commons IO
Example:
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.io.FileUtils;
public class HelpTest {
public static void main(String args[]) throws IOException, URISyntaxException {
String inputFilename = "test.txt"; // get from the user
//Im loading file from project
//You might load from somewhere else...
URI uri = HelpTest.class.getResource("/" + inputFilename).toURI();
String fileString = FileUtils.readFileToString(new File(uri));
// output file
File outputFile = new File("C:\\test.txt");
FileUtils.write(outputFile, fileString, true);
}
}

Append the file
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
new FileWriter(fileName,true);

A file channel that is open for writing may be in append mode .. http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html
also have a look at ..
http://docs.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)

Related

JAVA OCR to txt file

Good afternoon people,
With the help of research I did the code below to read texts of images:
package pckLeitor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Tess4jOCRv2 {
public static void main(String[] args) throws TesseractException {
File repository = new File("C:\\Users\\RAFSOUZA\\Desktop\\OCRTest");
try
{
for (File file : repository.listFiles()) {
String dtNow = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\RAFSOUZA\\Desktop\\Rafa3lOneiL\\BibliotecasExternasJAVA\\TesseractORC\\");
String fullText = tesseract.doOCR(file);
String fileExit = "C:\\Users\\RAFSOUZA\\Desktop\\OCRTest" + dtNow + ".txt";
FileWriter fstream = new FileWriter(fileExit);
BufferedWriter out = new BufferedWriter(fstream);
out.write(fullText);
out.newLine();
out.close();
}
}
catch (Exception e)
{
System.out.println("Ocorreu o seguinte erro" + e);
}
}
}
I would like to improve this code for:
1) Read all images in a folder
2) Generate a txt file with the data read from each image
Can you give me a direction?
Okay, so you've already gotten the code to read an image and output all text, right?
Let's try and wrap that with a loop or something using File#listFiles() and we should be ok!
Something like this should work, note I wrote this in notepad and it has not been tested!
import java.io.File;
public class Tess4jOCR {
public static void main(String[] args) throws TesseractException {
File repository = new File("C:\\Users\\RAFSOUZA\\Desktop\\OCRTest");
try {
for (File file : repository.listFiles()) {
String dtNow = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\RAFSOUZA\\Desktop\\Rafa3lOneiL\\BibliotecasExternasJAVA\\TesseractORC\\");
String fullText = tesseract.doOCR(file);
//String file = "O:\\Operações\\MIS\\Csa_OCR" + dtNow + ".txt";
String file = "C:\\RegistroRS" + dtNow + ".txt";
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//System.out.println(fullText);
out.write(fullText);
out.newLine();
out.close();
}
} catch (Exception e) {
System.out.println("Ocorreu o seguinte erro" + e);
}
}
}
Simply put all images you want to process in C:\\Users\\RAFSOUZA\\Desktop\\OCRTest (or whatever directory the repository variable is set to, and run it and it should output it to C:\\RegistroRS-<timestamp>.txt
Please note you may want to add additional logic to check filenames or maybe output the txt file in a name that's related to the original input so you don't reprocess things if you run the code more than once and you can easily tell which output came from which input.

Java input and output stream from file path

How does one use a specified file path rather than a file from the resource folder as an input or output stream? This is the class I have and I would like to read from a specific file path instead of placing the txt file in the resources folder in IntelliJ. Same for an output stream. Any help rendered would be appreciated thanks.
Input Stream
import java.io.*;
import java.util.*;
public class Example02 {
public static void main(String[] args) throws FileNotFoundException {
// STEP 1: obtain an input stream to the data
// obtain a reference to resource compiled into the project
InputStream is = Example02.class.getResourceAsStream("/file.txt");
// convert to useful form
Scanner in = new Scanner(is);
// STEP 2: do something with the data stream
// read contents
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
// STEP 3: be polite, close the stream when done!
// close file
in.close();
}
}
Output stream
import java.io.*;
public class Example03
{
public static void main(String []args) throws FileNotFoundException
{
// create/attach to file to write too
// using the relative filename will cause it to create the file in
// the PROJECT root
File outFile = new File("info.txt");
// convert to a more useful writer
PrintWriter out = new PrintWriter(outFile);
//write data to file
for(int i=1; i<=10; i++)
out.println("" + i + " x 5 = " + i*5);
//close file - required!
out.close();
}
}
Preferred way for getting InputStream is java.nio.file.Files.newInputStream(Path)
try(final InputStream is = Files.newInputStream(Paths.get("/path/to/file")) {
//Do something with is
}
Same for OutputStream Files.newOutputStream()
try(final OutputStream os = Files.newOutputStream(Paths.get("/path/to/file")) {
//Do something with os
}
Generally, here is official tutorial from Oracle to working with IO.
First you have to define the path you want to read the file from, absolute path like so:
String absolutePath = "C:/your-dir/yourfile.txt"
InputStream is = new FileInputStream(absolutePath);
It's similar for writing the file as well:
String absolutePath = "C:/your-dir/yourfile.txt"
PrintWriter out = new PrintWriter(new FileOutputStream(absolutePath));
You can use a file object as:
File input = new File("C:\\[Path to file]\\file.txt");

Read and Write with java from one file to another

How do I read the following information from a txt file and write just the numbers to another text file using Java? I have it displaying to the console but it will not write to the file also.
Jones 369218658389641
Smith 6011781008881301
Wayne 5551066751345482
Wines 4809134775860430
Biggie 9925689541232325
Luke 7586425896325410
Brandy 4388576018410707
Ryan 2458912425860439
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called cardnums.txt
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
}
}
I got it now.
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called credit.txt
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
output.flush();
output.close();
}
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
First of all why are you everytime calling this in loop with same filename?
Secondly, once you define it outside loop,
Call flush() on outputstream object and close if not null (preferabbly in finally block) after loop.
if(output!=null) {
output.flush();
output.close();
}
Here's a 1-liner:
Files.write(Paths.get("cardnums.txt"), () ->
Files.lines(Paths.get("accounts.txt"))
.map(s -> s.replaceAll("\\D", ""))
.collect(toList())
.iterator());
Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)

Java - How to remove blank lines from a text file

I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good

What is the simplest way to write a text file in Java?

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.

Categories