How to append multiple text in text file - java

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty

Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.

I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();

Make sure the second if condition is satisfied i.e. the line String contains "text2".

Related

How to read text file without the headline into ArrayList

I'm currently working on an assignment and I cannot find any clue to remove the headline from the text file and write the rest into an ArrayList. Can someone help me?
ID,Nama,GajiPokok,JmlAbsensi,JmlIzin
2,Peter,5000000,17,3
1,John,4500000,19,1
3,Linda,10000000,13,7
4,Lucy,7000000,20,0
Here is my code:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
try {
String line = in.readLine();
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
in.close();
} catch (IOException e){e.printStackTrace();}
If you want to ignore first line while reading the CSV file then you can simple skip processing of 1st line by calling in.readLine(); twice at the start as shown in below example:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
String line = in.readLine();
line = in.readLine(); //skip fist line and read second line
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
Using skip() method of JAVA 8 Streams:
try(BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"))) {
Stream<String> lines = in.lines();
List<Staff> staff = lines.skip(1).map(line -> {
Staff s = new Staff();
String data[] = line.split(",");
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setJmlhAbsensi(Integer.parseInt(data[3]));
s.setJmlhIzin(Integer.parseInt(data[4]));
return s;
}).collect(Collectors.toList());
System.out.println(staff);
}
You can declare the following line twice or initialize integer variable and skip the loop if its zero.
String line = in.readLine();
This solution works.
private void readTextFile(String fileName) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
Stream<String> stream = in.lines();
List<String> answer = stream.collect(Collectors.toList());
// For Pre-Java8
/*for (int i = 1; i < answer.size(); i++) {
System.out.println(answer.get(i));
}*/
// Split afterwards.
Stream<String> ans = answer.stream().filter(p -> !p.equals(answer.get(0)));
ans.forEach(x -> System.out.println(x));
}

Read from csv file with split missing in Java

I want to read csv file with BufferedReader and split with StringTokenizer. However there is one line in file which contains this line :
ide,12,office,,3208.83,0.18,577.5,4876
Also here is my read method;
public void readFromCSV(){
try {
File file = new File(myFile);
br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine()) != null) {
st1 = new StringTokenizer(line,"\n");
while(st1.hasMoreTokens()) {
oneLineList = new ArrayList<>();
st2 = new StringTokenizer(st1.nextToken(),",");
for(int i = 0; i < 8; i++) {
oneLineList.add(st2.nextToken());
}
dataList.add(counter,oneLineList);
}
counter++;
}
br.close();
}catch(IOException ex) {
ex.printStackTrace();
}
}
In for statement, there are 8 fields in each line, and dataList is a two-dimensional array list.
I cannot read whole data because of one line contain consecutive coma, how should I do for fix this?

Count the lines of several methods but return separate values not the sum of all

I'm going to elabortate my question because I had a hard time labeling the question the right way.
I'm labeling my methods like this:
/*Start*/
public void contadorDeLineas(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
I have several methods labeled like that but I want to count them separately, but the code I wrote counts the lines inside the methods starting from public and finishing in "Finish". But as for now the code I wrote counts all the lines inside the methods and return the sum of all the lines. What I want to do is read the first block return that value and continue searching for the next block of code.
This is the code I wrote
public void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
while((line = br.readLine())!=null){
if(line.startsWith("/*St")){
do{
line = br.readLine();
line = line.trim();
System.out.println(line);
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
}
}
br.close();
System.out.println("Found: " + lines_inside);
}
This is an example of what my code is showing in the console
/*Start*/
public void LineMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
/*Start*/
public static void main(String[] args)throws IOException{
program2 test = new program2();
File root = new File(args[0]);
test.LOC(root);
System.out.println("Found: " + test.lines);
System.out.println("Other type of lines: " + test.toDo);
}
}
/*Finish*/
Block comments lines: 11
Instead I'm looking for a result like a first print showing the number 3 and then a number 8.
Any guidance will be appreciated.
Try this
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
boolean inside = false;
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains("/*Start*/")) {
inside = true;
count = 0;
} else if (line.contains("/*Finish*/")) {
System.out.println("Found: " + count);
inside = false;
} else if (inside) {
++count;
}
}
if (inside && count > 0)
System.out.println("Found: " + count);
}
if you have several methods printing out all the lines may be to much when you are only interested in the number of lines. You can put the names of the methods and the number of lines in a map and print that out.
public static void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
Map<String, Integer> map = new HashMap<>();
while((line = br.readLine())!=null){
lines_inside = 0;
if(line.startsWith("/*St")){
String method = "";
do{
line = br.readLine();
if(line.contains("public")){
method = line.substring(0, ine.indexOf('('));
}
line = line.trim();
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
map.put(method, lines_inside);
}
}
br.close();
for(String s :map.keySet()){
System.out.println(s +" : "+ map.get(s));
}
}
Try to put lines_inside++; in the code like this:
while((line = br.readLine())!=null){
lines_inside++;
...
This gives you the rught number of elements in file.

Read text file line by line and store in a class?

I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.

BufferedReader to skip first line

I am using the following bufferedreader to read the lines of a file,
BufferedReader reader = new BufferedReader(new FileReader(somepath));
while ((line1 = reader.readLine()) != null)
{
//some code
}
Now, I want to skip reading the first line of the file and I don't want to use a counter line int lineno to keep a count of the lines.
How to do this?
You can try this
BufferedReader reader = new BufferedReader(new FileReader(somepath));
reader.readLine(); // this will read the first line
String line1=null;
while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
//some code
}
You can use the Stream skip() function, like this:
BufferedReader reader = new BufferedReader(new FileReader(somepath));
Stream<String> lines = reader.lines().skip(1);
lines.forEachOrdered(line -> {
...
});
File file = new File("path to file");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
int count = 0;
while((line = br.readLine()) != null) { // read through file line by line
if(count != 0) { // count == 0 means the first line
System.out.println("That's not the first line");
}
count++; // count increments as you read lines
}
br.close(); // do not forget to close the resources
Use a linenumberreader instead.
LineNumberReader reader = new LineNumberReader(new InputStreamReader(file.getInputStream()));
String line1;
while ((line1 = reader.readLine()) != null)
{
if(reader.getLineNumber()==1){
continue;
}
System.out.println(line1);
}
You can create a counter that contains the value of the starting line:
private final static START_LINE = 1;
BufferedReader reader = new BufferedReader(new FileReader(somepath));
int counter=START_LINE;
while ((line1 = reader.readLine()) != null) {
if(counter>START_LINE){
//your code here
}
counter++;
}
You can do it like this:
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
String[] wordsArray;
boolean skipFirstLine = true;
while(true){
line = buf.readLine();
if ( skipFirstLine){ // skip data header
skipFirstLine = false; continue;
}
if(line == null){
break;
}else{
wordsArray = line.split("\t");
}
buf.close();

Categories

Resources