Java PrintWriter printing multiple blank lines at the beginning of each file - java

I have used PrintWriter for long time and I have never encounted with this problem. See below
When I open the csv file using excel the first element of the headerline disapeared.
To further investigate, I found a couple of blank lines inserted at the beginning when opening it using text file.
below is my code:
print header line:
public void printHubInboundHeader() {
try {
StringBuilder sb = new StringBuilder();
String headingPart1 = "Inbound_Hub, Date, Time,";
String headingPart2 = "Weight";
sb.append(headingPart1+headingPart2);
System.out.println(sb);
FileWriter.writeFile(sb.toString(),"filepath");
}
catch(Exception e) {
System.out.println("Something wrong when writting headerline");
e.printStackTrace();
}
}
print actual data:
public void printHubSummary(Hub hub, String filePath) {
try {
StringBuilder sb = new StringBuilder();
String h = hub.getHub_code();
String date = Integer.toString(hub.getGs().getDate());
String time = hub.getGs().getHHMMFromMinute(hub.getGs().getClock());
String wgt = Double.toString(hub.getIb_wgt());
sb.append(h+","+date+","+time+","+wgt);
// System.out.println("truck print line: " + sb);
FileWriter.writeFile(sb.toString(),filePath);
}
catch (Exception e) {
System.out.println("Something wrong when outputing truck summary file!");
e.printStackTrace();
}
}
the file writer code:
public class FileWriter {
private static String filenameTemp;
public static boolean creatFile(String name) throws IOException {
boolean flag = false;
filenameTemp = name + "";
System.out.println("write to file: "+filenameTemp);
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
else {
filename.delete();
filename.createNewFile();
flag = true;
}
return flag;
}
public static boolean writeFile(String newStr, String filename) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filename);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
public static void setFileName(String fileName){
filenameTemp = fileName;
}
}

I don't know if this is the only problem with your code, but every call to your FileWriter.writeFile adds a new Byte Order Marker to the file. This means you end up with several markers in the file, and this may confuse some tools.
To remove the extra BOM in FileWriter.writeFile, you can use the deleteCharAt method:
...
buf = buf.append(System.getProperty("line.separator"));
}
if (buf.length() > 0 && buf.charAt(0) == '\uFEFF') {
buf.deleteCharAt(0);
}
buf.append(filein);

Related

Why can't I open this file in the assets folder? [duplicate]

I have may wifi2.txt file in my assets file directory in Android Studio. However, I keep getting a NULLPointException when I try to access it. My code is below: (Thanks so much in advance)
//CSV FILE READING
File file = null;
try {
FileInputStream is = new FileInputStream(file);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Done with CSV File Reading
In Kotlin, we can achieve this :-
val string = requireContext().assets.open("wifi2.txt").bufferedReader().use {
it.readText()
}
File file = null;
try {
FileInputStream is = new FileInputStream(file);
Actually you are not using FileInputStream anywhere. Just use this piece of code
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Method to read a file FROM assets:
public static String readFile(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
Usage: String yourData = LoadData("wifi2.txt");
Where wifi2.txt is assumed to reside in assets
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
Reference
My solution using kotlin to load text from asset file
object AssetsLoader {
fun loadTextFromAsset(context: Context, file: String): String {
return context.assets.open(file).bufferedReader().use { reader ->
reader.readText()
}
}
}
use it like this:
val text = AssetsLoader.loadTextFromAsset(context, "test.json")

Java, copy from a file to another, line by line with an interval

I have a file with 120 lines and I want to move them one by one to another file with an interval for example of 1 seconds and to be able to find after 10 seconds 10 lines in the new file.
But for my case, I execute the program with 0 lines in the new files until the end, and then I find the data.
String sourceFileName = "D:\\oldfile.txt";
String destinationFileName = "D:\\newfile.txt";
if(evt.getSource() == btnProcess)
{
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader(sourceFileName));
pw = new PrintWriter(new FileWriter(destinationFileName));
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
Thread.sleep(1000);
}
br.close();
pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
Second, for 4 files to process in the same moment with different interval, I need to use Threads ?
Thanks for your help.
When you are writing to a text file, PrintWriter does not write it to disk immediately. Instead, it keeps the data in a buffer in memory.
You could manually flush the buffer to when you need data to be on disk. Just after println() call flush() as below.
while ((line = br.readLine()) != null) {
pw.println(line);
pw.flush();
Thread.sleep(1000);
}
You can call a
pw.flush();
directly after
pw.println(line);
This should do the trick.
As for your second part, you could do something like this, if you do not want to use threads:
public static void main(final String[] args) {
FileCopyDto[] files = new FileCopyDto[] {
new FileCopyDto("D:\\oldfile.txt", "D:\\newfile.txt", 5),
new FileCopyDto("D:\\oldfile2.txt", "D:\\newfile2.txt", 1)
};
try {
boolean dataAvailable = true;
int secondCount = 0;
while (dataAvailable) {
dataAvailable = false;
for (FileCopyDto d : files) {
d.write(secondCount);
dataAvailable = dataAvailable || d.isDataAvailable();
}
secondCount++;
Thread.sleep(1000);
}
for (FileCopyDto d : files) {
d.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
static class FileCopyDto {
String sourceFileName;
String destinationFileName;
int timeInSeconds;
BufferedReader br = null;
PrintWriter pw = null;
String nextLine;
public FileCopyDto(final String sourceFileName,
final String destinationFileName,
final int timeInSeconds) {
this.sourceFileName = sourceFileName;
this.destinationFileName = destinationFileName;
this.timeInSeconds = timeInSeconds;
}
public void open() throws IOException {
br = new BufferedReader(new FileReader(sourceFileName));
pw = new PrintWriter(new FileWriter(destinationFileName));
}
public boolean isDataAvailable() throws IOException {
if (br == null) {
open();
}
return (nextLine == null) || ((nextLine = br.readLine()) != null);
}
public void write(final int secondCount) {
if (nextLine != null && secondCount % timeInSeconds == 0) {
pw.println(nextLine);
pw.flush();
nextLine = null;
}
}
public void close() throws IOException {
br.close();
pw.close();
br = null;
}
}

Making Java I / O and change the file to split in java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Read a file from a FTP server but InputStream is always null

I want read files in a directory. I want add in:
List<String> nomi = new ArrayList<String>();
the linestring of file Nomi.txt.
With debug i view correctly the files in links(001.jpg 002.jpg 003.jpg) and ft(Nomi.txt), but in stream i have always null;
InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
my complete code is this:
private static abstract class GetLinksTask extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... urls) {
List<String> links = new ArrayList<String>();
String ft=null;
BufferedReader reader = null;
List<String> nomi = new ArrayList<String>();
FTPClient f = new FTPClient();
try {
int reply;
f.connect(url_ftp);
f.login(username,password );
reply = f.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
f.disconnect();
System.err.println("FTP server refused connection.");
}
FTPListParseEngine engine = f.initiateListParsing("photo");
while (engine.hasNext()) {
FTPFile[] files = engine.getNext(25); // "page size" you want
//FTPFile[] files = engine.getFiles(filter);
for (FTPFile file : files) {
if(file.getName().substring(file.getName().length()-3,file.getName().length()).equals("jpg")){
System.out.println(file.getName());
links.add(file.getName());
}else{
ft=file.getName();
InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
//nomi.add(reader.readLine());
}
System.out.println(file.getName());
}
//names=nomi;
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null)
try {
reader.close();
}catch (IOException logOrIgnore) {
}
}
return links;
}
protected abstract void postExecute(List<String> links);
protected void onPostExecute(List<String> lists) {
postExecute(lists);
}
}
Some tips?
thanks
It is not enough to create a Reader
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
and to close it:
reader.close();
Somewhere, in between, you'll actually have to read the data:
String line;
while( (line = reader.readLine()) != null ){
nomi.add( line );
}
I am explaining the full code of getting inputStream from FTP server and then how to read data from that inputstream. I am assuming, you are using TLS/SSL security layer.
public FTPSClient makeFTPConnection(String vserver, int vport, String vuser, String vpassword) {
LOGGER.debug("ENTRY");
try {
ftpClient = new FTPSClient();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ftpClient.connect(vserver, vport);
ftpClient.login(vuser, vpassword);
ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.changeWorkingDirectory("/");
ftpClient.changeWorkingDirectory("/feeds");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
/* // int reply=ftpClient.getReply();
String replyStr=ftpClient.getReplyString();
ftpClient.getAuthValue();*/
LOGGER.debug("EXIT");
return ftpClient;
}
Then after making the connection, we will check weather file exist at ftp or not.
public InputStream checkWOFileExistAtFTP(FTPSClient ftpClient, String host,String user, String filePath) throws IOException {
int returnCode;
// filePath="ftp://"+user+"#"+host+"/"+filePath;
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
String dd=ftpClient.getReplyString();
returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
return null;
}
return inputStream;
}
Now we already got the inputStream in above method now its time to read data from it.
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("Reading file start.");
char[] charBuffer = new char[8 * 1024];
StringBuilder builder = new StringBuilder();
int numCharsRead;
while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
builder.append(charBuffer, 0, numCharsRead);
}
//will print all data
system.out.println(builder.toString());

Java reads ANSI file incorrectly

I tried to read an ANSI encoded Arabic file in Java using the following two way
Scanner scanner = null;
try {
scanner = new Scanner(new File("test/input.txt"), "ISO-8859-6");
while (scanner.hasNextLine()) {
String input =scanner.nextLine();
processString(input);
}
I tried also to read with default encoding (i.e. I omitted the "ISO-8859-6")
Any suggestions?
Try this code:
public static void transform(File source, String srcEncoding, File target, String tgtEncoding) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(source), Charset.forName(srcEncoding)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding));
char[] buffer = new char[16384];
int read;
while ((read = br.read(buffer)) != -1) {
bw.write(buffer, 0, read);
}
} finally {
try {
if (br != null) {
br.close();
}
} finally {
if (bw != null) {
bw.close();
}`enter code here`
}
}
}
Look at this:
private static final String FILENAME = "/Users/jucepho/Desktop/ansi.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This file has this characters http://www.alanwood.net/demos/ansi.html

Categories