I am trying to update a txt file in place, namely without creating a temp file or writing a file in a new file destination but I've tried all the solutions on stack overflow and none of these have worked so far.
It always give me an empty file as result. it simply delete all the content of the source file.
So I am trying to modify the following code, which takes two files as input, in order to take only one input (the file source) but without success.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class CopyFiles {
private static void copyFile(String sourceFileName, String destinationFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(sourceFileName));
PrintWriter pw = new PrintWriter(new FileWriter(destinationFileName))) {
String line;
while ((line = br.readLine()) != null) {
line += " ENDING ";
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String destinationFileName = "destination.csv";
String sourceFileName = "source.csv";
copyFile(sourceFileName, destinationFileName);
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So ive made a class to keep track of the data i've imported:
package com.company;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException{
String file = "Users/mathiaspoulsen/Desktop/SP3MarioPizza/pizzas.csv";
ArrayList <Pizza> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while ((line = br.readLine()) != null) {
line = br.readLine();
String [] lineArr = line.split(",");
Pizza pizza = new Pizza (Integer.parseInt(lineArr[0]),lineArr[1],Double.parseDouble(lineArr[2]));
content.add(pizza);
}
} catch (FileNotFoundException e) {
//Some error logging
}
return content;
}
I have then tried to run it in the main method to see if it loads the csv-file corectly. Like this:
package com.company;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
/* int i = 0;
String fileName = "pizzas.csv";
Path pathToFile = Paths.get(fileName);
System.out.println(pathToFile.toAbsolutePath());
*/
// ArrayList<Pizza> pizzas = ImportData.readData();
System.out.println(ImportData.readData());
}
}
The output of this program is: []
Why dont it display the pizzas? The pizzas in the csv-file a structured like this:
PizzaNumber(int),PizzaName(String), price(double)
1,MARGHERITA,69.00
You read the line multiple times which most likely was causing your issue just read the line once and check to make sure it is not null in the while statement before parsing it. Also, it would be better to check to make sure the parse is successful.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException {
String file = "/Users/your/path/pizza.csv";
ArrayList<Pizza> content = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] lineArr = line.split(",");
content.add(new Pizza(Integer.parseInt(lineArr[0]), lineArr[1], Double.parseDouble(lineArr[2])));
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
return content;
}
}
I have this code set up and I am trying to write a program that looks through a file and finds a specific hidden secret word then replaces the word with "found!" then re-prints the text file in the console. I know how to use reader and writer but I am unsure how i can use them in unison to do this. Code is as follows:
Reader Class:
package Main;
import java.io.*;
public class Read {
private static String line;
FileReader in;
File file;
public Read() {
line = "";
}
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
}
public String getLine() {
return line;
}
public File getFile() {
return file;
}
}
Writer(change) class:
package Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Change {
public static void main(String[] args) throws IOException{
Read r = new Read();
String line = r.getLine();
FileWriter fw = new FileWriter(r.getFile());
while(line != null) {
if(line.equals("example")) {
fw.write("found!");
}
System.out.println(line);
}
}
}
Am i on the right path or should i combine both of these into one class. Also is this the proper way of writing to a specific line in a text file?
If the file is a reasonable size, you can read it into memory, change what you need and write it back out again:
public static void replaceOccurrences(String match, String replacement, Path path) throws IOException {
Files.write(path, Files.lines(path).map(l -> {
if(l.contains(match)) {
return l.replace(match, replacement);
} else {
return l;
}
}).collect(Collectors.toList()));
}
Alternatively, if you know that the search term occurs only once and you just need to find the position of the occurrence, use the following:
try(BufferedReader reader = Files.newBufferedReader(path)) {
int lineIndex = 0;
String line;
while(!(line = reader.readLine()).contains(match)) {
lineIndex++;
}
System.out.println(lineIndex); // line which contains match, 0-indexed
System.out.println(line.indexOf(match)); // starting position of match in line, 0-indexed
}
If all you have to do is print the converted text to system out (rather than writing it out to a file), the second class isn't really needed. You can accomplish what you need in the readFile() method of the Read class:
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line.replaceAll("example", "found!"));
}
in.close();
}
There are a lot of other tweaks you could make, but that's the core of the functionality you specified in your question.
I am converting a pdf file to text and removing lines which have page number but the problem is that it leaving an empty space of 2 line.So i want to remove these spaces which have 2 or more empty line continuously but not if 1 line is empty.my code is :
// Open the file
FileInputStream fstream = new FileInputStream("C:\\Users\\Vivek\\Desktop\\novels\\Me1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String s=null;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String pattern = "^[0-9]+[\\s]*$";
strLine=strLine.replaceAll(pattern, " ");
writeResult("C:\\Users\\Vivek\\Desktop\\novels\\doci.txt",strLine);
}
//Close the input stream
br.close();
}
public static void writeResult(String writeFileName, String text)
{
File log = new File(writeFileName);
try{
if(log.exists()==false){
System.out.println("We had to make a new file.");
log.createNewFile();
}
PrintWriter out = new PrintWriter(new FileWriter(log, true));
out.append(text );
out.println();
out.close();
}catch(IOException e){
System.out.println("COULD NOT LOG!!");
}
}
plz help me.
You can work with sequent empty line counter in your method like SkrewEverything suggested.
Or make a post-processing with regular expressions like this:
package testingThings;
import java.awt.Desktop;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class EmptyLinesReducer {
public Path reduceEmptyLines(Path in) throws UnsupportedEncodingException, IOException {
Path path = Paths.get("text_with_reduced_empty_lines.txt");
String originalContent = new String(Files.readAllBytes(in), "UTF-8");
String reducedContent = originalContent.replaceAll("(\r\n){2,}", "\n\n");
Files.write(path, reducedContent.getBytes());
return path;
}
public Path createFileWithEmptyLines() throws IOException {
Path path = Paths.get("text_with_multiple_empty_lines.txt");
PrintWriter out = new PrintWriter(new FileWriter(path.toFile()));
out.println("line1");
//empty lines
out.println();
out.println();
out.println();
out.println("line2");
//empty lines
out.println();
out.println("line3");
//empty lines
out.println();
out.println();
out.println();
out.println();
out.println();
out.println("line4");
out.close();
return path;
}
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
EmptyLinesReducer app = new EmptyLinesReducer();
Path in = app.createFileWithEmptyLines();
Path out = app.reduceEmptyLines(in);
// open the default program for this file
Desktop.getDesktop().open(out.toFile());
}
}
I'm a beginner in Java. I have a 2 Java file that will passed the text retrieved from one Java file to the main Java file. But it doesnt seems to be working.
Main.java
import java.io.IOException;
public class LSAalgo extends Preprocessing {
public static void main(String[] args) throws IOException {
Preprocessing x = new Preprocessing(?);
}
}
Retrieve.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Preprocessing {
public void preprocessing(String text) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("input7.txt"));
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
}
}
Please help. Thanks.
You are just printing the text in console only. If you want to return complete text from one method to other just change your method return type to String (Since you are returning text) from void. Next change your code to
public String preprocessing() throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("input7.txt"));
String line = "";
while((line = in.readLine()) != null)
{
System.out.println(line);
line += line;//appending complete text
}
in.close();
return line;//returning text
}
In main(-) change code to call preprocessing() method of Preprocessing class.
Preprocessing x = new Preprocessing();
String text = x.preprocessing();//getting text from Preprocessing class
For example we have a .txt file:
Name smth
Year 2012
Copies 1
And I want to replace it with that:
Name smth
Year 2012
Copies 0
Using java.io.*.
Here is the code that does that. Let me know if you have any question.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test2 {
Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
File fileDir = new File("c:\\temp\\test.txt");
public static void main(String[] args) {
Test2 test = new Test2();
try {
test.readFileIntoADataStructure();
test.writeFileFromADataStructure();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readFileIntoADataStructure() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir)));
String line;
while ((line = in.readLine()) != null) {
if (line != null && !line.trim().isEmpty()) {
String[] keyValue = line.split(" ");
// Do you own index and null checks here this is just a sample
someDataStructure.put(keyValue[0], keyValue[1]);
}
}
in.close();
}
private void writeFileFromADataStructure() throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir)));
for (String key : someDataStructure.keySet()) {
// Apply whatever business logic you want to apply here
myBusinessMethod(key);
out.write(key + " " + someDataStructure.get(key) + "\n");
out.append("\r\n");
out.append("\r\n");
}
out.flush();
out.close();
}
private String myBusinessMethod(String data) {
if (data.equalsIgnoreCase("Copies")) {
someDataStructure.put(data, "0");
}
return data;
}
}
Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.
this is the code to do that
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.indexOf("Copies")>=0){
bw.write("Copies 0")
}
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close()bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
hopefully that help