It's not that my code doesn't work, but I am doubting whether it's very efficient or not. My theory is, that it isn't xD
I have a JTextPane where I have to take the text in it (Making a new line every time the JTextPane got a new line basically), and put it into a .txt file. As I said everything works but I am doubting the implementation of it.
This is the part I am doubting:
public void printLog() {
String s = logTextArea.getText();
ArrayList<String> log = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\n') {
sb.append(s.charAt(i));
} else {
log.add(sb.toString());
sb.delete(0, sb.length());
}
}
This is the entire thing just for reference:
public void printLog() {
String s = logTextArea.getText();
ArrayList<String> log = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\n') {
sb.append(s.charAt(i));
} else {
log.add(sb.toString());
sb.delete(0, sb.length());
}
}
File f = new File("JServer_Log.txt");
BufferedWriter bw = null;
FileWriter fr = null;
try {
if(f.exists()) {
fr = new FileWriter(f,true);
} else {
fr = new FileWriter(f);
}
} catch (IOException e) {
// Nothing to do really.
}
try {
bw = new BufferedWriter(fr);
Iterator<String> itr = log.iterator();
bw.newLine();
while(itr.hasNext()) {
bw.write(itr.next());
bw.newLine();
}
} catch (IOException e) {
// Nothing to do really. We lost the log?
} finally {
try {
bw.close();
} catch(IOException ioe) {
// The program is closing any way.
}
}
}
It seems that you just need to make sure you use the platform's appropriate newline sequence. You can just say s = s.replace("\n", System.getProperty("line.separator")) and then write that whole string directly to file. In fact, the way I see it, this is all the code you need (except maybe for exception handling, up to you):
public void printLog() throws IOException {
final FileWriter w = new FileWriter("JServer_Log.txt", true);
try {
w.write(logTextArea.getText().replace("\n",
System.getProperty("line.separator")));
} finally { w.close(); }
}
For information, the first code can be replaced by:
List<String> log = Arrays.asList(logTextArea.getText().split("\n"));
but other answers give you a way to replace the whole method.
Why bothering, to use JTextComponents.write(Writer out) throws IOExceptionwrite() this is pretty accepting newline, tabs, e.i. that came from Native OS
use split:
String[] log = s.split("\n");
Related
When I delete a record first before inserting a new record, I can do it, and after deleting I can add new record. But if I insert a new record first then my delete function is not working. Based on my research, it's mainly because the input/output is not closed properly but I have already done that, please take a look at my source code thank you.
Insert record
public void RegCustomer()
{
try
{
File F = new File("Customer.txt");
FileWriter fw = new FileWriter(F, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(F, true)));
pw.println(this.Name+","+this.CheckInDate+","+this.CheckOutDate+","+this.Floor+","+this.RoomID+","+this.ICNumber+","+this.Contact+","+this.Email);
pw.flush();
pw.close();
fw.close();
bw.close();
}
catch(Exception e)
{
}
}
Delete Record
public boolean delcus(String Target)
{
boolean success = false;
File F = new File("Customer.txt");
File Ftc = new File("Temp.txt");
try
{
FileReader fr = new FileReader(F);
BufferedReader br = new BufferedReader(fr);
PrintWriter pr = new PrintWriter(Ftc);
String line = br.readLine();
while (line!=null)
{
String[] wordsinLine = line.split(",");
if (wordsinLine[0].equals(Target))
{
}
else
{
pr.println(line);
success = true;
}
line = br.readLine();
}
if (success)
{
pr.flush();
pr.close();
br.close();
fr.close();
}
}
catch (Exception e)
{
}
F.delete();
File dump = new File("Customer.txt");
Ftc.renameTo(dump);
return success;
}
I have another method that checks for several conditions before triggering the insert method.
public int checkroom()
{
int check = 0;
int ciDay = this.CheckInDate/10000;
int ciMonth = (this.CheckInDate/100)%100;
int coDay = this.CheckOutDate/10000;
int days = coDay - ciDay;
String name;
int Dbcid;
int Dbcod;
int DbFloor;
int DbRoomID;
try
{
File F = new File("Customer.txt");
FileReader Fr = new FileReader(F);
BufferedReader Reader = new BufferedReader(Fr);
Scanner Sc = new Scanner(Reader);
Sc.useDelimiter("[,\n]");
while(Sc.hasNext())
{
name = Sc.next();
Dbcid = Sc.nextInt();
Dbcod = Sc.nextInt();
DbFloor = Sc.nextInt();
DbRoomID = Sc.nextInt();
if (days <= 7)
{
if (DbFloor == this.Floor && DbRoomID == this.RoomID)
{
int DbcidDay = Dbcid/10000;
int DbcidMonth = (Dbcid/100)%100;
int DbcodDay = Dbcod/10000;
if(ciMonth == DbcidMonth)
{
if (ciDay >= DbcidDay && ciDay < DbcodDay)
{
check = 2;
}
else if (coDay >= DbcidDay && coDay < DbcodDay)
{
check = 3;
}
else if (ciDay <= DbcidDay && coDay >= DbcodDay)
{
check = 4;
}
else
{
check = 1;
}
}
else
{
check = 1;
}
}
else
{
check =1;
}
}
else
{
check =5;
}
}
if(check > 0)
{
Sc.close();
Reader.close();
Fr.close();
}
}
catch (Exception e)
{
}
return check;
}
There are a few issues I can see:
You need to close your streams in a finally clause (or, better still, use a try-with-resource). Otherwise, if an exception is thrown that interrupts the normal program flow, your stream will not be closed immediately.
You should only close the outermost stream object (so e.g. your BufferedReader, but not the FileReader)
You are swallowing exceptions. At least do a printStackTrace() on the exceptions you catch so you can see if any are actually thrown.
Avoid methods like File.delete() that don't throw exceptions in the case of an error. Instead, use the equivalent methods on the Files.class, which throw exceptions in the event of an error.
Incidentally, although it's not an issue as such, you don't need to call flush() just before close()-- the latter automatically flushes before closing.
I'm having an issue with changing a line in a file, the purpose of this code is to change the first number of the file to itself + 1. For some reason the code doesn't seem to be functioning at all, any help would be appreciated!
public static void changenumber(String fileName)
{
ArrayList<String> list = new ArrayList<String>();
File temp = new File(fileName);
Scanner sc;
try {
sc = new Scanner(temp);
while (sc.hasNextLine())
{
list.add(sc.nextLine());
}
sc.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
String first = list.get(0);
int i = Integer.parseInt(first);
i = i+1;
first = Integer.toString(i);
list.set(0, first);
writenumber(list,fileName);
}
public static void writenumber(ArrayList<String> list, String fileName)
{
PrintWriter write;
try {
write = new PrintWriter(new FileWriter(fileName, true));
for(int i = 0; i<list.size();i++)
{
write.append(list.get(i));
}
}
catch(IOException err)
{
err.printStackTrace();
}
}
Your problem is that you never closed the FileWriter.
Use try-with-resources to ensure that file streams are closed correctly.
A few other improvements to your code:
Do not ignore exceptions. Continuing execution as-if nothing bad happened will cause lots of problems. Let the exception bounce back to caller, and let caller decide what to do if the file cannot be updated.
Scanner is slow. Since all you're doing to reading lines, use BufferedReader instead.
The lines in memory don't end in newline characters, so you need to use the println() method when writing the lines back out, otherwise the result is a file with all the lines concatenated into a single line.
Variables renamed to be more descriptive.
public static void changenumber(String fileName) throws IOException {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
for (String line; (line = in.readLine()) != null; ) {
lines.add(line);
}
}
int i = Integer.parseInt(lines.get(0));
i++;
lines.set(0, Integer.toString(i));
writenumber(lines, fileName);
}
public static void writenumber(List<String> lines, String fileName) throws IOException {
try (PrintWriter out = new PrintWriter(new FileWriter(fileName, true))) {
for (String line : lines) {
out.println(line);
}
}
}
Of course, you could simplify the code immensely by using the newer NIO.2 classes added in Java 7, in particular the java.nio.file.Files class.
public static void changenumber(String fileName) throws IOException {
Path filePath = Paths.get(fileName);
List<String> lines = Files.readAllLines(filePath);
lines.set(0, Integer.toString(Integer.parseInt(lines.get(0)) + 1));
Files.write(filePath, lines);
}
I'm new to coding in Java. I put together this piece of code to read all lines between the "Start" and "End" tag in the following text file.
Start
hi
hello
how
are
you
doing?
End
My program is as follows....
package test;
import java.io.*;
public class ReadSecurities {
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileInputStream in = new FileInputStream("U:\\Read101.txt");
FileOutputStream out = new FileOutputStream("U:\\write101.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
BufferedReader br = new BufferedReader(new InputStreamReader(in));
for (int i=1; i<=countLines("U:\\Read101.txt"); i++) {
String line=br.readLine();
while (line.contains("Start")) {
for (int j=i; j<=countLines("U:\\Read101.txt"); j++) {
String line2=br.readLine();
System.out.println(line2);
if(line2.contains("End")) break;
else {
bw.write(line2);
bw.newLine();
}
bw.close();
} break;
}
}
br.close();
}
catch (Exception e) { }
finally { }
}
}
The program reads only the first two lines "hi hello" as though the if condition does not exist. I have a feeling the mistake is very basic, but please correct me.
String line;
do{ line = br.readLine(); }
while( null != line && !line.equals("Start"));
if ( line.equals("Start") ) { // in case of EOF before "Start" we have to skip the rest!
do{
line = br.readLine();
if ( line.equals("End") ) break;
// TODO write to other file
}while(null != line )
}
Should be as easy as that. I left out creation / destruction of resources and proper Exception handling for brevity.
But please do at least log exceptions!
EDIT:
If EOF is encountered before Start, you have to skip the copy step!
You make one crucial mistake in your code: you don't handle the exceptions correctly. Two things:
never catch Exception. Either catch just one type of Exception or specify a list of exceptions you want to catch. In your case, a simple IOException would suffice.
Never leave a catch-block empty. Either throw a new exception, return a value or - in your case - print the exception with e.printStackTrace().
When you do these two things, you will notice that your code throws an IOException, because you close your bw-Stream too early. Move the bw.close() down to where br.close() is.
Now, when you have done that, your code is almost working. The only thing is - you now get a NullPointerException. This is because you don't change your line after all entries are read. The easy fix to this is change from
while(line.equals("Start")) { ...
to
if(line.equals("Start")) { ...
Also, there are some other not-so-neat things in your code, but I will leave it for now - experience comes with time.
For Java 8:
List<String> stopWords = Arrays.asList("Start", "End");
try (BufferedReader reader = new BufferedReader(input))) {
List<String> lines = reader.lines()
.map(String::trim)
.filter(s -> !StringUtils.isEmpty(s) && !stopWords.contains(s))
.collect(Collectors.toList());
}
I have a text file with the following format:
String1
String1String2
String1String2String3
....
String1Strin2String3.....String(i)...String(n)
I want to remove some parts of this file to have the following format(result file):
String1
String2
String3
...
String(i)
String(n)
I tried with this fonction but my output file is always empty:
public static void FileFormatted(String inputFile,String outputFile)
{
String FileContent = readFile(inputFile,
StandardCharsets.UTF_8);
String[] FileSentences = FileContent.split("[\n]");
for (int i = 0; i < FileSentences.length; i++)
{
StringBuilder builder = new StringBuilder();
for(int j=1;j<FileSentences.length;j++)
{
int index= FileSentences[j].indexOf("FileSentences[i]");
String temp=FileSentences[j].substring(index);
FileSentences[j]=FileSentences[j].replaceAll(temp," ");
builder.append(FileSentences[j]+ "\n");
}
writeIntoFile(builder, outputFile, true);
}
}
public static void writeIntoFile(StringBuilder stringBuilder,
String txtFilePath, boolean append) {
File file = new File(txtFilePath);
// if file doesn't exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw;
try {
fw = new FileWriter(file.getAbsoluteFile(), append);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stringBuilder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone please help me.
Okay, first of all reading the whole file in, in one go is bad practice. Imagine you have a 6gb file, that means you need 6gb of RAM to store that file when you read it in. It would be better to read the file line by line.
So the Aim of the logic would be read line by line.
When we read the first line we can get the length of it.
When we read read the second line we know the length of the first line so that means it is our starting point on the second line. This means you can use sub-string method, passing the start position and end position.
And repeat this logic for line 3,4,...n
The benefit of this is that you don't waste memory, you are only storing the size of the line in text.
Update
I have written the code that I suggested earlier. It's pretty basic and there is no validation so you will need to add to it. But it covers the basics
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fileReader);
int startPosition = 0;
String line;
ArrayList<String> items = new ArrayList<String>();
while((line = br.readLine() ) != null)
{
items.add(line.substring(startPosition, line.length()));
System.out.println(line.substring(startPosition, line.length()));
startPosition = line.length();
}
write("test2.txt", items);
}
public static void write (String filename, ArrayList<String> items) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (String item : items) {
outputWriter.write(item);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
be sure the pattern is consistent in the hole file, then Do this:
public static void main(String[] args) {
String wordTofind = "String";
String st = "String1String2String3String4";
String[] arra = st.split(wordTofind);
for (int i = 1; i < arra.length - 1; i++) {
System.out.println(wordTofind + arra[i]);
//write to a file or similar.
}
}
you can use regex too, but this is acceptable...
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 7 years ago.
Improve this question
I have made a class that can save an array to file, yet, I need it to load the file back into an array inside of an Activity named SampleGridViewAdapter.
Text file format named gallerydump_img.txt:
https://mywebsite.com/path/samplefile.rtf
https://anotherwebsite.com/
https://thirdwebsite.com/example/
I have tried strings = LIST[i], with strings being the output from the file, i being the loop, and LIST being the array to output the file data to, line by line. More code below:
#Override
protected void onPostExecute(String[] strings) {
for(int i = 0; i < strings.length; i++) {
Log.e("GalleryFileDump", strings[i]);
ArrayToFile.writeArrayToFile(strings, Environment.getExternalStorageDirectory() + "/gallerydump_img.txt", "Eww, errors. Want a cookie? :: Unable to write to file gallerydump.bin. Check the report below for more information. :)");
strings = LIST[i]
}
}
Any help appreciated. Thanks!
This is what you'd want to read
public static List<String> readLines() {
File f = new File("gallerydump_img.txt");
BufferedReader r;
List<String> lines = new ArrayList<String>();
try {
r = new BufferedReader(new FileReader(f));
String line;
while (true) {
if ((line = r.readLine()) == null)
break;
lines.add(line);
}
} catch (Exception e) {
e.printStackTrace(); // file not found
}
return lines;
}
And this is what you'd want to write
public static void writeLines(List<String> lines) {
File f = new File("gallerydump_img.txt");
try {
PrintWriter pw = new PrintWriter(f);
for (String line : lines)
pw.println(line);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); // file not found
}
}
I'm guessing what you have above doesn't compile? That's fine if it doesn't. I just want to be sure I understand the question.
Anyways, one way to serialize and deserialize strings to a file are as follows:
String[] readFile(String filename)
{
String[] strings;
BufferedReader reader = null;
try
{
reader = new BufferedReader( new InputStreamReader( new FileInputStream(filename)));
String str = reader.readLine();
while( null != str )
{
strings.add(str);
str = reader.readLine();
}
}
catch( IOException e )
{
e.printStackTrace();
}
if( null != reader )
{
reader.close();
}
return strings.toArray(new String[strings.size()]);
}
void writeFile(String filename, String[] strings )
{
PrintWriter writer = null;
try
{
writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename)));
for( int idx = 0; idx < strings.length; idx++ )
{
writer.println(strings[idx]);
}
}
catch( IOException e )
{
e.printStackTrace();
}
if( null != writer )
{
writer.close();
}
}