when i run the program the second time my Record.txt gets empty .
i think i'm getting this error in the file reader but i dont know what to do with it.
if you guys can give me a hint i'll appreciate it.
File file = new File("D:\\Program Files\\Oracle\\program\\Record.txt");
if (file.length() <= 0) {
try {
FileReader fr = new FileReader(
"D:\\Program Files\\Oracle\\program\\inventory.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
while ((datas = br.readLine()) != null) {
String[] d = datas.split(",");
int a = Integer.parseInt(d[1]);
int b = Integer.parseInt(d[2]);
items.add(new list(d[0], a, b));
}
br.close();
fr.close();
} catch (IOException | NumberFormatException e) {
System.out.println("Error");
}
}
Iterator itemit = items.iterator();
try {
FileWriter fw = new FileWriter(
"D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedWriter bw = new BufferedWriter(fw);
itemit = items.iterator();
while (itemit.hasNext()) {
list l = (list) itemit.next();
System.out.println(l.ingname + l.qty + l.ingid);
if (item1 == 1 && l.ingid == 100) {
l.qty = l.qty - item1qty;
}
if (item2 == 1 && l.ingid == 200) {
l.qty = l.qty - item2qty;
}
bw.write(l.ingname + ":" + l.qty + ":" + l.ingid);
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException e) {
System.out.println("Error");
}
else{
try{
FileReader fr = new FileReader("D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
//System.out.println(file.length());
while((datas = br.readLine()) != null){
String[] d = datas.split(",");
int x = Integer.parseInt(d[1]);
items.add(new list(d[0],x));
}
br.close();
fr.close();
}catch(IOException | NumberFormatException e){
System.out.println("Error");
}
}
From the code parts you provided it looks like the items list is only filled with entries from inventory.txt if the Record.txt file is empty. If it is not empty (f.e. when running the program for a second time) items is probably empty and thus the content of Record.txt will overwritten.
Currently your code looks like this
if (Record.txt file is emtpy) {
read inventory file into items
}
write items to record file
// where is the corresponding if?!
else {
read Record.txt file
}
and is should probably look like this
if (Record.txt file is emtpy) {
read inventory file into items
write items to record file
}
else {
read Record.txt file
}
Related
I'm just a beginner and got the following task:
Write first 100 positive and 100 negative integers to the file, listing them separated by a space.
Then read this file and put the read numbers into 2 files: positive_numbers and negative_numbers.
public static void main(String[] args) throws IOException {
File numbers = new File("C:\\numbers.txt");
File positivNumbers = new File("C:\\positivnumbers.txt");
File negativNumbers = new File("C:\\negativnumbers.txt");
try (
BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));
BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
if (numbers.exists()) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I could write numbers as a String to file "numbers". But I cannot read and write them in "positiv" output file.The file is empty. Where is my mistake?
After the writing you have to close wr so all data in memory gets flushed to the file. AFTER the close you can reopen it for read. So in your code you open rd too soon.
try (BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
} catch (IOException e) {
e.printStackTrace();
}
// file is closed by try-with-resources ...
// ... so now we can open it for read:
try (BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
// TODO : split logic
}
} catch (IOException e) {
e.printStackTrace();
}
I've got the file, which can vary in size, in terms of lines. The only thing I know is that it's made of same modules of, lets say, 7 lines. So it means that .txt can be 7, 14, 21, 70, 77 etc. lines. I need to get only header of each module - line 0, 7 and so on.
I've written this code for the job:
textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );
List<String> headers = new ArrayList<>();
if (textFile.exists()) {
try {
FileInputStream fs= new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
int lines = 0;
int headLine = 0;
while (reader.readLine() != null) { lines++;}
Log.i("Debug", Integer.toString(lines));
while(headLine < lines){
for (int i = 0; i < dateLine - 1; i++)
{
reader.readLine();
Log.i("Debug", reader.readLine());
}
headers.add(reader.readLine());
headLine += 7;
}
Log.i("Debug", headers.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that it always returns [null]. I do not know where's the problem, since I used similar questions from overflow as references.
ArrayList<String> headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
// process the line.
if(lineCount % 7 == 0) {
heaaderLines.add(line);
}
lineCount ++;
}
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
br.close();
}
i want to print the output in new line how to do this?
Below is the output.
CHILD: Child line one oneCHILD: Child line one twoCHILD: Child line one three
CHILD: Child line two oneCHILD: Child line two twoCHILD: Child line two three
here is my code for it...
try {
fis = new FileInputStream(file);
fileWriterChild = new FileWriter(outputFileForChild);
brChild = new BufferedWriter(fileWriterChild);
fr = new FileReader(file);
br = new BufferedReader(fr);
int child_line_no = 0;
int buffer = 0;
String currentLine = br.readLine();
while (currentLine != null) {
if (currentLine.contains("CHILD:")) {
Files.write(Paths.get("C:/output.child.txt"),
currentLine.getBytes(), StandardOpenOption.APPEND);
}
currentLine = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
fis.close();
}
}
Depends on what do you want to do. Here are my two ways:
Appending one line to the end of file
void WriteLog(String date, String message) {
String logFileName = <path to file>;
File logFile = new File(logFileName);
//make directories
logFile.getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(logFile, true)) {
writer.write(message);
writer.write("\r\n");
} catch (IOException ex) {
Cls_log.LogError("Error writing log - " + ex.toString());
}
}
Writing all strings as lines to file (overwriting file)
public static void WriteABcardLog(Map<String,String> etiquetteCache) {
File logFile = new File(<path to file>);
logFile.getParentFile().mkdirs();
try (PrintWriter writer = new PrintWriter(logFile)) {
Iterator<Map.Entry<String, String>> iterator = etiquetteCache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
try {
writer.print(entry.getKey() + ";" + entry.getValue() + "\r\n");
} catch (NullPointerException e) {
Cls_log.LogError(e);
}
}
writer.println();
} catch (IOException ex) {
Cls_log.LogError("Error writing etiquette log - " + ex.toString());
}
}
I want to split csv file into multiple csv files depending on column value.
Structure of csv file: Name,Id,Dept,Course
abc,1,CSE,Btech
fgj,2,EE,Btech
(Rows are not separated by ; at end)
If value of Dept is CSE or ME , write it to file1.csv, if value is ECE or EE write it to file2.csv and so on.
Can I use drools for this purpose? I don't know drools much.
Any help how it can be done?
This is what I have done yet:
public void run() {
String csvFile = "C:/csvFiles/file1.csv";
BufferedReader br = null;
BufferedWriter writer=null,writer2=null;
String line = "";
String cvsSplitBy = ",";
String FileName = "C:/csvFiles/file3.csv";
String FileName2 = "C:/csvFiles/file4.csv";
try {
writer = new BufferedWriter(new FileWriter(FileName));
writer2 = new BufferedWriter(new FileWriter(FileName2));
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] values=line.split(cvsSplitBy);
if(values[2].equals("CSE"))
{
writer.write(line);
}
else if(values[2].equals("ECE"))
{
writer2.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
writer.flush();
writer.close();
writer2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1) First find column index using header row or if header is not present then by index
2) Follow below algorithm which will result map of key value where key is column by which split is performed
global resultMap;
Method add(key,row) {
data = (resultMap.containsKey(key))? resultMap.get(key):new ArrayList<String>();
data.add(row);
resultMap.put(key, data );
}
Method getSplittedMap(List rows) {
for (String currentRow : rows) {
add(key, currentRow);
}
return resultMap;
}
hope this helps.
FileOutputStream f_ECE = new FileOutputStream("provideloaction&filenamehere");
FileOutputStream f_CSE_ME = new FileOutputStream("provideloaction&filenamehere");
FileInputputStream fin = new FileinputStream("provideloaction&filenamehere");
int size = fin.available(); // find the length of file
byte b[] = new byte[size];
fin.read(b);
String s = new String(b); // file copied into string
String s1[] = s.split("\n");
for (int i = 0; i < s1.length; i++) {
String s3[] = s1[i].split(",")
if (s3[2].equals("ECE"))
f_ECE.write(s1.getBytes());
if (s3[2].equals("CSE") || s3.equals("EEE"))
f_CSE_ME.write(payload.getBytes());
}
Can anyone point me in the right direction here. I have a method that is supposed to read a file and display the data in that file. I can only get it to display one line. I know it is something simple I am over looking, but my brain is mush and I just keep digging a bigger hole.
public static String readFile(String file) {
String data = "";
if (!new java.io.File(file).exists()) {
return data;
}
File f = new File(file);
FileInputStream fStream = null;
BufferedInputStream bStream = null;
BufferedReader bReader = null;
StringBuffer buff = new StringBuffer();
try {
fStream = new FileInputStream(f);
bStream = new BufferedInputStream(fStream);
bReader = new BufferedReader(new InputStreamReader(bStream));
String line = "";
while (bStream.available() != 0) {
line = bReader.readLine();
if (line.length() > 0) {
if (line.contains("<br/>")) {
line = line.replaceAll("<br/>", " ");
String tempLine = "";
while ((tempLine.trim().length() < 1)
&& bStream.available() != 0) {
tempLine = bReader.readLine();
}
line = line + tempLine;
}
buff.append(line + "\n");
}
}
fStream.close();
bStream.close();
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buff.toString();
}
String line = null;
while ((line = bReader.readLine())!=null)
How about doing this with Guava:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html
List<String> lines = Files.readLines("myFile.txt", Charset.forName("UTF-8"));
System.out.println(lines);
You'd still have to do a little bit of work to concatenate the <br> lines etc...