I have some content in an input file a.txt as
Line 1 : "abcdefghijk001mnopqr hellohello"
Line 2 : "qwertyuiop002asdfgh welcometologic"
Line 3 : "iamworkingherefromnowhere002yes somethingsomething"
Line 4 : "thiswillbesolved001here ithink"
I have to read the a.txt file and write it to two separate files. ie., lines having 001 should be written to output1.txt and lines having 002 should be written to output2.txt
Can someone help me on this with a logic in Java programming.
Thanks,
Naren
BufferedReader br = new BufferedReader( new FileReader( "a.txt" ));
String line;
while(( line = br.readLine()) != null ) {
if( line.contains( "001" )) sendToFile001( line );
if( line.contains( "002" )) sendToFile002( line );
}
br.close();
The method sendToFile001() and sendToFile002() write the parameter line as follow:
ps001.println( line );
with ps001 and ps002 of type PrintStream, opened before (in a constructor?)
Here is a good example for Reading and writing text files using Java and checking conditions do the following
while ((line = reader.readLine()) != null) {
//process each line in some way
if(line.contains("001") {
fileWriter1.write(line);
} else if (line.contains("002") ) {
fileWriter2.write(line);
}
}
Code complete.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
/**
*
* #author andy
*/
public class JFile {
/**
* #param args the command line arguments
*/
static File master = null,
m1 = null, // file output with "001"
m2 = null; // file output with "002"
static FileWriter fw1,
fw2;
static FileReader fr = null;
static BufferedReader br = null;
public static void main(String[] args) throws FileNotFoundException, IOException
{
String root = System.getProperty("user.dir") + "/src/files/";
master = new File ( root + "master.txt" );
m1 = new File ( root + "m1.txt");
m2 = new File ( root + "m2.txt");
fw1 = new FileWriter(m1, true);
fw2 = new FileWriter(m2, true);
fr = new FileReader (master);
br = new BufferedReader(fr);
String line;
while((line = br.readLine())!=null)
{
if(line.contains("001"))
{
fw1.write(line + "\n");
} else if (line.contains("002"))
{
fw2.write(line + "\n");
}
}
fw1.close();
fw2.close();
br.close();
}
}
Project Netbeans : http://www.mediafire.com/?yjdtxj2gh785cyd
Related
I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.
Where Iam Going Wrong?? No Matter What I do It Says Null Pointer Exception on String.replace()
I want To replace a Charecter From File And Write The Changed Content To Other File.. even though its easy i am unable to write it.Help Please!
package tinku;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Scanner;
/**
*
* #author gajasurve
*/
public class Tinku {
static int i;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String str;
final String Y;
String Key;
FileOutputStream fos = new FileOutputStream("/home/gajasurve/Desktop/done2.txt");
DataOutputStream output = new DataOutputStream(fos);
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n Enter Complete File Path with Extension (ex: /home/gajasurve/Desktop/info.txt) : ");
String Source;
Source=r.readLine();
System.out.print("Enter Key Element to Find In the File ");
Key=r.readLine();
File f= new File(Source);
LineNumberReader lr= new LineNumberReader(new FileReader(f));
while((str=lr.readLine())!=null)
{
if(str.contains(Key))
{
i=lr.getLineNumber();
System.out.print("The Entered Key Element Can B Found In " + i + " Line");
}
}
System.out.println("Do u wish to change the Key Element? Y|N");
String Dec= r.readLine();
switch (Dec) {
case "Y" :
System.out.print("Enter New Key Element to Replace");
String d2;
d2 = r.readLine();
str= str.replaceAll(Key, d2); //NPE here
System.out.println(str);
break;
}
}
}
When you run your while loop, the exit condition is that the loop ends when str becomes null, hence when you are trying to access str the next time it is null and so gives a NullPointerException.
You can fix it by running a similar while loop around the replaceAll() code, or you can move everything until the replaceAll() method call inside the while loop. (Note: this will ask if you want to replace the Key for every occurrence)
Possible Fixed Code:
package tinku;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
/**
*
* #author gajasurve
*/
public class Tinku {
static int i;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String str;
final String Y;
String Key;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n Enter Complete File Path with Extension (ex: /home/gajasurve/Desktop/info.txt) : ");
String Source;
Source = br.readLine();
File f= new File(Source);
LineNumberReader lr= new LineNumberReader(new FileReader(f));
System.out.print("Enter Key Element to Find In the File : ");
Key = br.readLine();
while((str = lr.readLine()) != null) {
if(str.contains(Key)) {
i = lr.getLineNumber();
System.out.println("The Entered Key Element Can B Found In " + i + " Line");
}
}
lr.close();
System.out.println("Do u wish to change the Key Element? Y|N");
String Dec= br.readLine();
switch(Dec) {
case "Y" : {
System.out.print("Enter String to replace Key with : ");
String d2;
d2 = br.readLine();
lr= new LineNumberReader(new FileReader(f));
String outputFile = "/home/gajasurve/Desktop/done2.txt";
PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
while((str = lr.readLine()) != null) {
if(str.contains(Key)) {
pw.println(str.replaceAll(Key, d2));
} else {
pw.println(str);
}
}
pw.close();
break;
}
}
}
}
I have a text file sample.txt which have following lines
sample1.txt
test.ppt
example.doc
content.pdf
I have a dynamic variable called field (example phpcookbook.pdf,sample1.txt) it should compare with each line in sample.txt file and if the text file does not contain the field it should append to sample.txt. I have tried the following code but it's not working:
File insert=new File(sample.txt);
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if(!strLine.equals(field)) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
}
I should get the following output
sample1.txt
test.ppt
example.doc
content.pdf
phpcookbook.pdf
How to compare a text file line by line with a dynamic variable?
If I understand the question correctly, this is what you need:
File insert = new File("sample.txt");
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
Boolean hasLine = false;
while ((strLine = br.readLine()) != null) {
if(strLine.equals(field)) {
hasLine = true;
break;
}
}
br.close();
if (!hasLine) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field + "\n"); // assumes field does not already have a newline
bw.flush();
bw.close();
}
Notice the break;. This will discontinue the while loop, since you already have the answer to what you are looking for.
Your original code was doing:
for every line:
Do I equal field?
Yes: goto next line
No: append field to file and goto next line
But what you WANTED to know was whether or not field appeared in the file at all, not in each line.
You should use Commons IO.
See this working example
package training;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class TestFile {
/**
* #param args
* #throws IOException
*/
private static String field = "phpcookbook.pdf";
private static String fileContent;
public static void main(String[] args) throws IOException {
boolean found = false;
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
if (line.equals(field)) {
found = true;
break;
}
}
if (!found) {
fileContent = FileUtils.readFileToString(file);
fileContent += "\n" + field;
}
FileUtils.write(file, fileContent);
}
}
You should do something like this:
File insert = new File("sample.txt");
boolean isStringPresent = false;
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.equals(field)) {
isStringPresent = true;
}
}
if(!isStringPresent) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
No answer since you ask for Java, but just to illustrate the power of Unix shell tools:
v=phpcookbook.pdf
grep $v in.txt
[[ $? -eq 1 ]] && echo $v >> in.txt
I have a hdd array with 4 encrypted hard-drives (truecrypt). I recently switched back from 5 years of linux to windows 7 and I find myself confronted with a problem I can't find a solution for.
Under linux there was a command called "fdisk" which gives you all running (not mounted!) harddrives plus a unique disk-identifier which doesn't change (something like: Disk Identifier: 00x33f1a3c1).
I need that same functionality under Windows, preferably writing the code in java.
cheers
edit:// For clarification, I need the Disk-ID without mounting the Disk!
A solution using VBS.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DiskUtils {
private DiskUtils() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = DiskUtils.getSerialNumber("C");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, sn, "Serial Number of C:",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
I have a linux server and many clients with many operating systems. The server takes an input file from clients. Linux has end of line char LF, while Mac has end of line char CR, and
Windows has end of line char CR+LF
The server needs as end of line char LF. Using java, I want to ensure that the file will always use the linux eol char LF. How can I achieve it?
Could you try this?
content.replaceAll("\\r\\n?", "\n")
Combining the two answers (by Visage & eumiro):
EDIT: After reading the comment. line.
System.getProperty("line.separator") has no use then.
Before sending the file to server, open it replace all the EOLs and writeback
Make sure to use DataStreams to do so, and write in binary
String fileString;
//..
//read from the file
//..
//for windows
fileString = fileString.replaceAll("\\r\\n", "\n");
fileString = fileString.replaceAll("\\r", "\n");
//..
//write to file in binary mode.. something like:
DataOutputStream os = new DataOutputStream(new FileOutputStream("fname.txt"));
os.write(fileString.getBytes());
//..
//send file
//..
The replaceAll method has two arguments, the first one is the string to replace and the second one is the replacement. But, the first one is treated as a regular expression, so, '\' is interpreted that way. So:
"\\r\\n" is converted to "\r\n" by Regex
"\r\n" is converted to CR+LF by Java
Had to do this for a recent project. The method below will normalize the line endings in the given file to the line ending specified by the OS the JVM is running on. So if you JVM is running on Linux, this will normalize all line endings to LF (\n).
Also works on very large files due to the use of buffered streams.
public static void normalizeFile(File f) {
File temp = null;
BufferedReader bufferIn = null;
BufferedWriter bufferOut = null;
try {
if(f.exists()) {
// Create a new temp file to write to
temp = new File(f.getAbsolutePath() + ".normalized");
temp.createNewFile();
// Get a stream to read from the file un-normalized file
FileInputStream fileIn = new FileInputStream(f);
DataInputStream dataIn = new DataInputStream(fileIn);
bufferIn = new BufferedReader(new InputStreamReader(dataIn));
// Get a stream to write to the normalized file
FileOutputStream fileOut = new FileOutputStream(temp);
DataOutputStream dataOut = new DataOutputStream(fileOut);
bufferOut = new BufferedWriter(new OutputStreamWriter(dataOut));
// For each line in the un-normalized file
String line;
while ((line = bufferIn.readLine()) != null) {
// Write the original line plus the operating-system dependent newline
bufferOut.write(line);
bufferOut.newLine();
}
bufferIn.close();
bufferOut.close();
// Remove the original file
f.delete();
// And rename the original file to the new one
temp.renameTo(f);
} else {
// If the file doesn't exist...
log.warn("Could not find file to open: " + f.getAbsolutePath());
}
} catch (Exception e) {
log.warn(e.getMessage(), e);
} finally {
// Clean up, temp should never exist
FileUtils.deleteQuietly(temp);
IOUtils.closeQuietly(bufferIn);
IOUtils.closeQuietly(bufferOut);
}
}
Here is a comprehensive helper class to deal with EOL issues. It it partially based on the solution posted by tyjen.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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 org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
/**
* Helper class to deal with end-of-line markers in text files.
*
* Loosely based on these examples:
* - http://stackoverflow.com/a/9456947/1084488 (cc by-sa 3.0)
* - https://github.com/apache/tomcat/blob/main/java/org/apache/tomcat/buildutil/CheckEol.java (Apache License v2.0)
*
* This file is posted here to meet the "ShareAlike" requirement of cc by-sa 3.0:
* http://stackoverflow.com/a/27930311/1084488
*
* #author Matthias Stevens
*/
public class EOLUtils
{
/**
* Unix-style end-of-line marker (LF)
*/
private static final String EOL_UNIX = "\n";
/**
* Windows-style end-of-line marker (CRLF)
*/
private static final String EOL_WINDOWS = "\r\n";
/**
* "Old Mac"-style end-of-line marker (CR)
*/
private static final String EOL_OLD_MAC = "\r";
/**
* Default end-of-line marker on current system
*/
private static final String EOL_SYSTEM_DEFAULT = System.getProperty( "line.separator" );
/**
* The support end-of-line marker modes
*/
public static enum Mode
{
/**
* Unix-style end-of-line marker ("\n")
*/
LF,
/**
* Windows-style end-of-line marker ("\r\n")
*/
CRLF,
/**
* "Old Mac"-style end-of-line marker ("\r")
*/
CR
}
/**
* The default end-of-line marker mode for the current system
*/
public static final Mode SYSTEM_DEFAULT = ( EOL_SYSTEM_DEFAULT.equals( EOL_UNIX ) ? Mode.LF : ( EOL_SYSTEM_DEFAULT
.equals( EOL_WINDOWS ) ? Mode.CRLF : ( EOL_SYSTEM_DEFAULT.equals( EOL_OLD_MAC ) ? Mode.CR : null ) ) );
static
{
// Just in case...
if ( SYSTEM_DEFAULT == null )
{
throw new IllegalStateException( "Could not determine system default end-of-line marker" );
}
}
/**
* Determines the end-of-line {#link Mode} of a text file.
*
* #param textFile the file to investigate
* #return the end-of-line {#link Mode} of the given file, or {#code null} if it could not be determined
* #throws Exception
*/
public static Mode determineEOL( File textFile )
throws Exception
{
if ( !textFile.exists() )
{
throw new IOException( "Could not find file to open: " + textFile.getAbsolutePath() );
}
FileInputStream fileIn = new FileInputStream( textFile );
BufferedInputStream bufferIn = new BufferedInputStream( fileIn );
try
{
int prev = -1;
int ch;
while ( ( ch = bufferIn.read() ) != -1 )
{
if ( ch == '\n' )
{
if ( prev == '\r' )
{
return Mode.CRLF;
}
else
{
return Mode.LF;
}
}
else if ( prev == '\r' )
{
return Mode.CR;
}
prev = ch;
}
throw new Exception( "Could not determine end-of-line marker mode" );
}
catch ( IOException ioe )
{
throw new Exception( "Could not determine end-of-line marker mode", ioe );
}
finally
{
// Clean up:
IOUtils.closeQuietly( bufferIn );
}
}
/**
* Checks whether the given text file has Windows-style (CRLF) line endings.
*
* #param textFile the file to investigate
* #return
* #throws Exception
*/
public static boolean hasWindowsEOL( File textFile )
throws Exception
{
return Mode.CRLF.equals( determineEOL( textFile ) );
}
/**
* Checks whether the given text file has Unix-style (LF) line endings.
*
* #param textFile the file to investigate
* #return
* #throws Exception
*/
public static boolean hasUnixEOL( File textFile )
throws Exception
{
return Mode.LF.equals( determineEOL( textFile ) );
}
/**
* Checks whether the given text file has "Old Mac"-style (CR) line endings.
*
* #param textFile the file to investigate
* #return
* #throws Exception
*/
public static boolean hasOldMacEOL( File textFile )
throws Exception
{
return Mode.CR.equals( determineEOL( textFile ) );
}
/**
* Checks whether the given text file has line endings that conform to the system default mode (e.g. LF on Unix).
*
* #param textFile the file to investigate
* #return
* #throws Exception
*/
public static boolean hasSystemDefaultEOL( File textFile )
throws Exception
{
return SYSTEM_DEFAULT.equals( determineEOL( textFile ) );
}
/**
* Convert the line endings in the given file to Unix-style (LF).
*
* #param textFile the file to process
* #throws IOException
*/
public static void convertToUnixEOL( File textFile )
throws IOException
{
convertLineEndings( textFile, EOL_UNIX );
}
/**
* Convert the line endings in the given file to Windows-style (CRLF).
*
* #param textFile the file to process
* #throws IOException
*/
public static void convertToWindowsEOL( File textFile )
throws IOException
{
convertLineEndings( textFile, EOL_WINDOWS );
}
/**
* Convert the line endings in the given file to "Old Mac"-style (CR).
*
* #param textFile the file to process
* #throws IOException
*/
public static void convertToOldMacEOL( File textFile )
throws IOException
{
convertLineEndings( textFile, EOL_OLD_MAC );
}
/**
* Convert the line endings in the given file to the system default mode.
*
* #param textFile the file to process
* #throws IOException
*/
public static void convertToSystemEOL( File textFile )
throws IOException
{
convertLineEndings( textFile, EOL_SYSTEM_DEFAULT );
}
/**
* Line endings conversion method.
*
* #param textFile the file to process
* #param eol the end-of-line marker to use (as a {#link String})
* #throws IOException
*/
private static void convertLineEndings( File textFile, String eol )
throws IOException
{
File temp = null;
BufferedReader bufferIn = null;
BufferedWriter bufferOut = null;
try
{
if ( textFile.exists() )
{
// Create a new temp file to write to
temp = new File( textFile.getAbsolutePath() + ".normalized" );
temp.createNewFile();
// Get a stream to read from the file un-normalized file
FileInputStream fileIn = new FileInputStream( textFile );
DataInputStream dataIn = new DataInputStream( fileIn );
bufferIn = new BufferedReader( new InputStreamReader( dataIn ) );
// Get a stream to write to the normalized file
FileOutputStream fileOut = new FileOutputStream( temp );
DataOutputStream dataOut = new DataOutputStream( fileOut );
bufferOut = new BufferedWriter( new OutputStreamWriter( dataOut ) );
// For each line in the un-normalized file
String line;
while ( ( line = bufferIn.readLine() ) != null )
{
// Write the original line plus the operating-system dependent newline
bufferOut.write( line );
bufferOut.write( eol ); // write EOL marker
}
// Close buffered reader & writer:
bufferIn.close();
bufferOut.close();
// Remove the original file
textFile.delete();
// And rename the original file to the new one
temp.renameTo( textFile );
}
else
{
// If the file doesn't exist...
throw new IOException( "Could not find file to open: " + textFile.getAbsolutePath() );
}
}
finally
{
// Clean up, temp should never exist
FileUtils.deleteQuietly( temp );
IOUtils.closeQuietly( bufferIn );
IOUtils.closeQuietly( bufferOut );
}
}
}
Use
System.getProperty("line.separator")
That will give you the (local) EOL character(s). You can then use an analysis of the incomifile to determine what 'flavour' it is and convert accordingly.
Alternatively, get your clients to standardise!
public static String normalize(String val) {
return val.replace("\r\n", "\n")
.replace("\r", "\n");
}
For HTML:
public static String normalize(String val) {
return val.replace("\r\n", "<br/>")
.replace("\n", "<br/>")
.replace("\r", "<br/>");
}
solution to change the file ending with recursive search in path
package handleFileLineEnd;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import sun.awt.image.BytePackedRaster;
public class handleFileEndingMain {
static int carriageReturnTotal;
static int newLineTotal;
public static void main(String[] args) throws IOException
{
processPath("c:/temp/directories");
System.out.println("carriageReturnTotal (files have issue): " + carriageReturnTotal);
System.out.println("newLineTotal: " + newLineTotal);
}
private static void processPath(String path) throws IOException
{
File dir = new File(path);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
if (child.isDirectory())
processPath(child.toString());
else
checkFile(child.toString());
}
}
}
private static void checkFile(String fileName) throws IOException
{
Path path = FileSystems.getDefault().getPath(fileName);
byte[] bytes= Files.readAllBytes(path);
for (int counter=0; counter<bytes.length; counter++)
{
if (bytes[counter] == 13)
{
carriageReturnTotal = carriageReturnTotal + 1;
System.out.println(fileName);
modifyFile(fileName);
break;
}
if (bytes[counter] == 10)
{
newLineTotal = newLineTotal+ 1;
//System.out.println(fileName);
break;
}
}
}
private static void modifyFile(String fileName) throws IOException
{
Path path = Paths.get(fileName);
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("\r\n", "\n");
content = content.replaceAll("\r", "\n");
Files.write(path, content.getBytes(charset));
}
}
Although String.replaceAll() is simpler to code, this should perform better since it doesn't go through the regex infrastructure.
/**
* Accepts a non-null string and returns the string with all end-of-lines
* normalized to a \n. This means \r\n and \r will both be normalized to \n.
* <p>
* Impl Notes: Although regex would have been easier to code, this approach
* will be more efficient since it's purpose built for this use case. Note we only
* construct a new StringBuilder and start appending to it if there are new end-of-lines
* to be normalized found in the string. If there are no end-of-lines to be replaced
* found in the string, this will simply return the input value.
* </p>
*
* #param inputValue !null, input value that may or may not contain new lines
* #return the input value that has new lines normalized
*/
static String normalizeNewLines(String inputValue){
StringBuilder stringBuilder = null;
int index = 0;
int len = inputValue.length();
while (index < len){
char c = inputValue.charAt(index);
if (c == '\r'){
if (stringBuilder == null){
stringBuilder = new StringBuilder();
// build up the string builder so it contains all the prior characters
stringBuilder.append(inputValue.substring(0, index));
}
if ((index + 1 < len) &&
inputValue.charAt(index + 1) == '\n'){
// this means we encountered a \r\n ... move index forward one more character
index++;
}
stringBuilder.append('\n');
}else{
if (stringBuilder != null){
stringBuilder.append(c);
}
}
index++;
}
return stringBuilder == null ? inputValue : stringBuilder.toString();
}
Since Java 12 you can use
var str = str.indent(0);
which implicitly normalizes the EOF characters.
Or more explicitly
var str = str.lines().collect(Collectors.joining("\n", "", "\n"))