public static void doubleSpace(String fileName) {
try {
FileReader reader = new FileReader(fileName);
Scanner in = new Scanner(reader);
String outputFileName = fileName.charAt(0) + ".ds";
PrintWriter pOut = new PrintWriter(outputFileName);
// Opening of files for input and output
while (in.hasNextLine()) {
String line = in.nextLine();
pOut.println(line + "\n");
pOut.print("\n");
// System.out.println(line + "\n"); //Test
}
pOut.close(); // Close the files if they have been opened.
} catch (Exception e) {
}
}
So basically my input file contains
a
b
c
and my output file should look like
a
b
c
However, my output file always contains only abc.
Any help would be much appreciated!
Use a BufferedWriter. It has a .newLine() method. This method will use the platform's default line separator.
And use a BufferedReader. It has a .readLine() method.
Example:
// NOTE: you should really be using UTF-8
final Charset charset = Charset.defaultCharset();
final Path src = Paths.get(filename);
final Path dst = Paths.get(filename + ".ds");
String line;
try (
final BufferedReader reader = Files.newBufferedReader(src, charset);
final BufferedWriter writer = Files.newBufferedWriter(dst, charset);
) {
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
writer.newLine();
}
}
You are likely useing the wrong character(s) for new line for your plattform. Use
System.getProperty("line.separator");
to get the right value.
Related
Basic explanation:
I'm coding a simple java utility which will take xml file and convert it into html. All xml files have same structure and need to be converted into same looking HTML file so i chose to code it using BufferedReader and Writer, see code below.
I'm having following problem If i'm using file that is on local disk, than there is no problem and everything workes fine, but when i try to use file that is on connected shared network disk, code throws exception.
this is whole code
reading and writting file that is stored in project folder workes just fine and just as i want to, i'm only having problem with file stored on network disk.
public static void main(String[] args) {
String cestaKsuboruXml = "file.xml"; //workes fine
//this one throws error
// String cestaKsuboruXml = "\\172.27.20.38\eDesk\2017\0925\144f7d8d-3786-4858-95ef-bb853c41b713\1_PridelenieCislaPodania.xml";
//class which contains html code
sablonaJedna sablonaJedna = new sablonaJedna();
String fileName = null ;
String line = null;
StringBuilder text = new StringBuilder();
StringBuilder subject = new StringBuilder();
try {
FileReader fileReader = new FileReader(cestaKsuboruXml);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(cestaKsuboruXml), "UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("<subject>")) {
subject.append(line);
}
if (!line.contains("<GeneralAgenda") && !line.contains("<subject>"))
{
text.append(line);
}
}
} catch (IOException ex) {
System.out.println("Exception");
}
String text2 = text.toString();
String subject2 = subject.toString();
subject2 = subject2.replace("<subject>", "");
subject2 = subject2.replace("</subject>", "");
text2 = text2.replace("<text>", "");
text2 = text2.replace("</text>", "");
text2 = text2.replace("</GeneralAgenda>", "");
try {
BufferedWriter writer = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream("vvvaa.html", true), "UTF-8"));
writer.write(sablonaJedna.getSablonaCss() + sablonaJedna.getSablonaHtml() + subject2 +
"</span></div><div class=\"clear\"> </div><div><label class=\"labelVis\">Text: </label> <span class=\"contentVis wordwrap\">"
+ text2 + "</span></div><div class=\"clear\"> </div></div></div></body></html>"
);
writer.close();
} catch (IOException xx) {
System.out.println("Exception");
}
}
all i had to do was use this as a source:
String cestaKsuboruXml = "\\\\172.27.20.38\\eDesk\\2017\\0925\\144f7d8d-3786-4858-95ef-bb853c41b713\\1_PridelenieCislaPodania.xml";
so two more backslashes at the start of a link
I've a code which replaces 10:A to 12:A in a text file called sample.txt. Also, the code I've now is changing the file format, which shouldn't. Can someone please let me know how to do the same using regular expression in Java which doesn't change the file format? File has original format as below 10:A 14:Saxws But after executing the code it outputs as 10:A 14:Saxws.
import java.io.*;
import java.util.*;
public class FileReplace
{
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("sample.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null)
{
if (line.contains("10:A"))
line = line.replaceAll("10:A", "12:A") + System.lineSeparator();
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
It looks like your OS or editor is not able to print correctly line separators generated by System.lineSeparator(). In that case consider
reading content of entire file to string (including original line separators), - then replacing part which you are interested in
and writing replaced string back to your file
You can do it using this code:
Path file = Paths.get("sample.txt");
//read all bytes from file (they will include bytes representing used line separtors)
byte[] bytesFromFile = Files.readAllBytes(file);
//convert themm to string
String textFromFile = new String(bytesFromFile, StandardCharsets.UTF_8);//use proper charset
//replace what you need (line separators will stay the same)
textFromFile = textFromFile.replaceAll("10:A", "12:A");
//write back data to file
Files.write(file, textFromFile.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
I have written java code to remove initial characters from a file with 200k records , the file is removing the initial characters but its reading the file line by line and removing the characters .The program is executing very slow . Any tweaks could be made to below code to execute it faster ?
The program is executing and writing the output to a file , but its very slow
import java.io.*;
import java.util.Scanner;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
File input = new File(inputfile);
Scanner scan = new Scanner(input);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while (scan.hasNext()) {
line = scan.nextLine();
line = line.substring(number_of_char_to_erased);
print.println(line);
}
scan.close();
print.close();
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
What appears to be the issue here is that you just created a buffered reader to read the file. Then, it reads the first line of the file. Then, you create a Scanner to read ALL the lines in the file, omitting certain characters. Then your BufferedReader reads the next line in the file. And the process repeats itself. So all you have to do is this:
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
print.println(line.substring(number_of_char_to_erased);
}
print.close();
This should much faster. Basically, since you've already allocated line to the read line from the file, you can simply print out that line, minus the number of chars, to the output file. The entire for loop with scanner was entirely unnecessary, and closing and opening the print stream for each line was also unnecessary.
EDIT: Removed the println statement since it would slow it down a bit.
Try this (Scanner and Println removed, output file refactored outside the loop):
import java.io.*;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
String trimmedLine = line.substring(number_of_char_to_erased);
print.println(trimmedLine);
}
// Always close files.
bufferedReader.close();
print.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
I have method which writes some data to file. I use PrintWriter, BufferedWriter and FileWriter as shown below
public void writeToFile(String FileName){
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
for(Cars car : list){
pw.println(car.getType());
pw.println(car.getMaxSpeed());
pw.println(car.getOwner());
pw.println();
pw.flush();
}
pw.close();
}
catch(IOException ex){
System.err.println(ex);
}
}
Now how can I read this data from file? I tried to use InputStreamReader, BufferedReader and FileInputStream, but my NetBeans shows me an error message
public void readFromFile() throws IOException {
InputStreamReader fr = null;
try {
fr = new InputStreamReader(new BufferedReader(new FileInputStream(new FileReader("c:\\cars.txt"))));
System.out.println(fr.read());
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
fr.close();
}
}
What is wrong with this method?
BufferedReader in = new BufferedReader(new FileReader("file.in"));
BufferedWriter out = new BufferedWriter(new FileWriter("file.out"));
String line = in.readLine(); // <-- read whole line
StringTokenizer tk = new StringTokenizer(line);
int a = Integer.parseInt(tk.nextToken()); // <-- read single word on line and parse to int
out.write(""+a);
out.flush();
There are several problems in your code :
1) An InputStreamReader takes an InputStream as an argument not a Reader. See http://docs.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html.
2) The FileInputStream does not accept a Reader as argument as well (it takes a File, a FileDescriptor, or a String). See : http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html
3) A BufferedReader reads the File line by line normally. The read() method only reads a single character.
A possible solution could be :
fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File("c:\\cars.txt"))));
String line = "";
while((line = fr.readLine()) != null) {
System.out.println(line);
}
Btw : It would be easier for others to help you, if you provide the exact error-message or even better the StackTrace.
Simple error: Cannot resolve constructor 'FileInputStream(java.io.FileReader)', required constructor not exist in API.
Your original code was:
new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
so for reading, you need
new PrintReader(new BufferedReader(new FileReader(FileName)));
but PrintReader is not needed (not exist), so all you need is:
new BufferedReader(new FileReader(FileName))
PrinterWriter prints formatted representations of objects to a text-output stream, but when reading text is always formatted, so PrinterReader not exist.
You are writing line by line, so also read line by line :) Example:
public void readFromFile() throws IOException {
BufferedReader bufferedReader = null;
try {
String sCurrentLine;
bufferedReader = new BufferedReader(new FileReader("c:\\cars.txt"));
while ((sCurrentLine = bufferedReader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
bufferedReader.close();
}
}
or better (JDK7)
void readFromFile() throws IOException {
Path path = Paths.get("c:\\cars.txt");
try (BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset())){
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}