Java - Help needed with file reading - java

public void readFile() throws IOException
{
try (BufferedReader reader = new BufferedReader(new FileReader("Data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
DefaultTableModel model = (DefaultTableModel) pracListTeacherTable.getModel();
model.addRow(new Object[]{line, line});
}
Hey everyone. I have this piece of code that essentially reads from a file called Data.txt. What I want is for each 2 lines of the text file to create 1 row on the table, however as you can see I'm using model.addRow(new Object[]{line, line}); which uses the same line for both cells of the same Row.
I need some way to store the previous line so I can have something like model.addRow(new Object[]{line, nextline}); however I can't figure out how to do it!
If anyone could help me out that would be amazing.
Update: Got it working thanks to shaoyihe!
public void readFile() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader("Data.txt"))) {
String line1, line2;
while ((line1 = reader.readLine()) != null && (line2 = reader.readLine()) != null) {
DefaultTableModel model = (DefaultTableModel) pracListTeacherTable.getModel();
model.addRow(new Object[]{line1,line2});
}
}

What about read two lines at every loop ?
String line1, line2;
while ((line1 = reader.readLine()) != null && (line2 = reader.readLine()) != null) {
//model.addRow(new Object[]{line1, line2});
}
// for odd line
if (line1 != null) {
}

This should do it:
public void readFile() throws IOException
{
try (BufferedReader reader = new BufferedReader(new FileReader("Data.txt"))) {
String line;
String [] lines = new String[2];
int nextLine = 0;
while ((line = reader.readLine()) != null) {
System.out.println(line);
lines[nextLine++] = line;
// check if we're at the second line
if (nextLine == 2) {
DefaultTableModel model = (DefaultTableModel) pracListTeacherTable.getModel();
model.addRow(lines);
nextLine = 0;
}
}
if (nextLine == 1) {
// odd number of lines in file (error?)
// lines[0] contains the odd (last) line
// lines[1] contains the previous line (last of the previous pair)
}
}
Would it make sense to retrieve the model once before the loop? or does getModel() return a different model on each call?

Related

Fill Array From Text File Depending On Character's Gender

I want to fill an array with names. The array should be filled depending on what gender the character is.
public void fillNameArray() throws IOException {
Character character = new Character(); //Declare and initialise character object
if(character.getGender() == "F"){
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("femaleNames.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = (String[]) lines.toArray();
}
else{
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("maleNames.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = (String[]) lines.toArray();
}
}
The problem is in the following line:
String[] array = (String[]) lines.toArray();
Write instead:
String[] array = lines.toArray(new String[lines.size()]);
See post as example.
Please can you also move the read code on a own method? So less code duplication.
public List<String> readNames(String file) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
return lines;
}

How can I select string after = operator in a file?

I have a file containing following text:
CompanyName=IBM
Name=User1234
CompanyName=Google
How can check if a text 'CompanyName' exists in a text file, if it does then select a string after = operator?. So the text from above file should output IBM and Google.
while ((line = br.readLine()) != null) {
System.out.println(line);
}
You can use java.util.Properties
Properties properties = new Properties();
properties.load(new InputStreamReader
(new FileInputStream("myprops.properties"), StandardCharsets.UTF_8));
String property = properties.getProperty("CompanyName");
Would it be something like this?
while ((line = br.readLine()) != null) {
System.out.println(line);
if(line.contains("CompanyName"))
{
String[] splits = line.split("=");
String desired = splits[1]; // second position in the string array.
}
}
EDIT: adding more functionality in getting the other fields at the same time.
while ((line = br.readLine()) != null)
{
System.out.println(line);
String compName = "";
String name = "";
if(line.contains("CompanyName"))
{
String[] splits2 = line.split("=");
compName = splits2[1]; // second position in the string array.
if((line = br.readLine()) != null)
{
String[] splits = line.split("=");
name = splits[1];
}
}
}
Here is how you can do it:
function findValueOfAttr(String attr, br) {
while ((line = br.readLine()) != null) {
if (line.indexOf(attr) == 0)
return line.subString(line.indexOf("=")+1);
}
return false;
}

mark & reset in java BufferedReader

I want to use mark() and reset() method to read the line before divider.
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
while ((line = br.readLine()) != null) {
boolean endOfObj = false;
while (!line.trim().contains(DIVIDER)) {
br.mark(line.length());
line = br.readLine(); //return next line
}
br.reset();
line = br.readLine();
but line variable value is not the previous line of divider.
what is my problem is .
thank you
Could you try using the following code? I tidied up your code a bit, and put it into a method called getPreviousLine(). I got the feeling that you were getting hung up on using mark() and reset(), so I just relied on pure logic and state to find the line before the divider. If no divider is found, the method will return null.
String getPreviousLine(String PATH) {
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
boolean endOfObj = false;
String previousLine = br.readLine();
if (previousLine == null) {
return null;
}
while ((line = br.readLine()) != null) {
if (line.trim().contains(DIVIDER)) {
endOfObj = true; // found the divider; break
break;
} else {
previousLine = line; // advance your line pointer
}
}
if (endOfObj) {
return previousLine;
} else {
return null;
}
}

readLine() null return

I have the following code:
public static void main(String[] args) throws Exception {
String s = "";
StringBuilder sb = new StringBuilder();
File file = new File("C:\\New\\r.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
while(in.readLine() != null) {
sb.append(in.readLine());
}
System.out.println(sb);
s = sb.toString();
byte[] b = s.getBytes();
for(int i = 0; i < b.length; i++) {
if(b[i] == 1){ b[i]=0; }
if(b[i] == 0){ b[i]=1; }
}
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.write(b);
in.close();
fos.close();
dos.close();
}
I get a return of null when I run this program. Maybe I must elevate the program? Help would be appreciated.
Change:
while(in.readLine()!=null)
to:
while((s = in.readLine())!=null)
and then:
sb.append(s);
When you call in your code to in.readLine() twice - you're reading two lines but printing only the second in each iteration.
You're throwing away every odd line:
while(in.readLine()!=null)
{
sb.append(in.readLine());
}
If r.txt only contains one line, you will get the string "null" in the StringBuffer, because the first line of StringBuffer.append does this:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
....
}
If there are two lines, you will get the first line with "null" at the end of the line.
The following will append all lines from the file to the StringBuffer:
String line = null;
while((line = in.readLine()) != null)
{
sb.append(line);
}
your code
while(in.readLine() != null) {
sb.append(in.readLine());
}
change with it
while ((s = in.readLine()) != null)
{
sb.append(s);
}

Make FileReader read every fourth line with a loop

My problems is that I have to arrange, when searching for a customer, arrange the while loop to only examine every fourth line read.
This is the code I already have on this problem:
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
while ((line = br.readLine()) != null)
{
...
}
br.close();
Does anybody know what needs to be at the place of "..."?
Thanks!
Something along the lines of
int i = 0;
while ((line = br.readLine()) != null)
{
i++;
if (i % 4 == 0)
{
// if i is divisible by 4, then
// your actual code will get executed
...
}
}
Just call br.readLine() 3 times at the end of the loop, discarding the output:
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
while ((line = br.readLine()) != null)
{
...
for(int i=0;i<3;i++){ br.readLine(); }
}
br.close();
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
int count 0;
while ((line = br.readLine()) != null)
{
if (count!=3)
count++;
else {
// Do something?
count=0;
}
}
br.close();

Categories

Resources