How do you write to a file in java? - java

This is a code snippet that shows me trying to write to a file.
public void printContents() {
int i = 0;
try {
FileReader fl = new FileReader("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
i = i + 1;
}
scn.close();
} catch (IOException exc) {
exc.printStackTrace();
} catch (Exception exc) {
exc.printStackTrace();
}
}
public void writeContents() {
try {
//FileOutputStream formater = new FileOutputStream("Product List.txt",true);
Formatter writer = new Formatter(new FileOutputStream("Product List.txt", false));
for (int i = 0; i < 2; ++i) {
writer.format(productList[i].name + "", (productList[i].price + 200.0 + ""), (productList[i].number - 1), "\n");
}
writer.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
The exception thrown while trying to run this code is:
java.util.NoSuchElementException at ReadingAndWritting.printContents(ReadingAndWritting.java:37).
I tried multiple things and only ended up with: "cokefruitgushersAlnassma" in the file. What I want is:
coke 7.95 10
fruitgushers 98.00 6
Alnassma 9.80 7

The Problem seems to be in
String productName = scn.next();
// Here:
double productPrice = scn.nextDouble();
// And here:
int productAmount = scn.nextInt();
After scn.next(), you don't check if scn.hasNext() before requesting the next element (double or int, respectively). So, either your file is not complete, or not in the exact structure you expect, or you just missed the two additional checks before trying to work with data which just isn't there.
Solution could be like:
while (scn.hasNext()) {
String productName = scn.next();
if ( scn.hasNext() ) {
double productPrice = scn.nextDouble();
if ( scn.hasNext() ) {
int productAmount = scn.nextInt();
// Do something with the three values read...
} else {
// Premature end of file(?)
}
} else {
// Premature end of file(?)
}
}

Related

twitter4j search for full 7 day range

I try to save tweets with keywords, I know that free API gives only 7 days of the result, but it never gets any set of a timeline greater than few hours, sometimes it even gives me a range of an hour. I did set since() and until() to the searching query. The maximum number of the tweets I've got from a single run was less than 400. And can anyone tell me why it stopped automatically with such few results? Thanks.
public static void main(String[] args) throws TwitterException {
String KEY_word;
String Exclude;
String Since;
String Until;
String OPT_dir;
String time;
int x;
Propertyloader confg = new Propertyloader();
KEY_word = confg.getProperty("KEY_word");
Exclude = confg.getProperty("Exclude");
Since = confg.getProperty("Since");
Until = confg.getProperty("Until");
OPT_dir = confg.getProperty("OPT_dir");
Twitter twitter = new TwitterFactory().getInstance();
try {
time = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
x = 1;
Query query = new Query(KEY_word + Exclude);
query.since(Since);
query.until(Until);
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
try {
String filedir = OPT_dir + KEY_word + time;
writeStringToFile(filedir, x + ". " + "#" + tweet.getUser().getScreenName() + ", At: " + tweet.getCreatedAt() + ", Rt= " + tweet.getRetweetCount() + ", Text: " + tweet.getText());
x += 1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
public static void writeStringToFile(String filePathAndName, String stringToBeWritten) throws IOException{
try
{
String filename= filePathAndName;
boolean append = true;
FileWriter fw = new FileWriter(filename,append);
fw.write(stringToBeWritten);//appends the string to the file
fw.write("\n" +"\n");
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
You can get more tweets by using setMaxId. Here is an example :
long lowestTweetId = Long.MAX_VALUE;
x = 1;
Query query = new Query("stackoverflow");
query.since("2018-08-10");
query.until("2018-08-16");
query.setCount(100); //The number of tweets to return per page, up to a maximum of 100. Defaults to 15. https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
query.setResultType(Query.RECENT); // to get an order
int searchResultCount=100;
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
try {
System.out.println( "#" + tweet.getUser().getScreenName() + ", At: " + tweet.getCreatedAt() );
x += 1;
if (tweet.getId() < lowestTweetId) {
lowestTweetId = tweet.getId();
query.setMaxId(lowestTweetId-1);
}
else {// each new maxid should be smaller than the other one so break here
//do whatever you want to handle it ex: break from two loops
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} while (searchResultCount != 0 );

How do I reopen an account in java, using a constructor with differnt argument lengths?

I want to print the existing balance and name of the account, but when I put the two inside of the arguments it draws an error: args of different lengths. What will make the this.balance and this.nm appear on the form side of the program when I open an existing account?
public abstract class AssetAccount implements Account{
public int AcctNo;
public double balance;
public String actmsg,errmsg;
public String nm, typecd;
public double rate;
NumberFormat c = NumberFormat.getCurrencyInstance();
public AssetAccount(String typecd, String nm, double sbal) {
this.AcctNo = 0;
this.actmsg = "";
this.errmsg = "";
this.balance= 0;
this.typecd = typecd;
while (this.AcctNo == 0) {
try {
this.AcctNo = (int) (Math.random() * 1000000);
BufferedReader in = new BufferedReader(
new FileReader(this.typecd + this.AcctNo + ".txt"));
in.close();
this.AcctNo = 0;
} catch (IOException e) {
//'good' result: account does not yot exist....
this.nm = nm;
this.balance = sbal;
writestatus();
if (this.errmsg.isEmpty()) {
actmsg = this.typecd + "Account " +
this.nm + " " + this.AcctNo + " opened.";
writelog(actmsg);
}
if (!this.errmsg.isEmpty()) {
this.balance = 0;
this.AcctNo = -1;
this.typecd = "";
}
} catch (Exception e) {
errmsg = "Fatal error in Account constructor: " +
e.getMessage();
this.AcctNo = -1;
this.typecd = "";
}
}//end of while
}//end of constructor
public AssetAccount(String typecd, int acctno) {
//constructor for known acct number
errmsg = "";
actmsg = "";
// need to get the balance and name so that it shows when re opened
this.typecd = typecd;
this.AcctNo = acctno;
try {
BufferedReader in = new BufferedReader(
new FileReader( typecd + acctno + ".txt"));
actmsg = this.nm + "Account " + acctno + " re-opened.";
} catch (Exception e) {
errmsg = "Error re-opening account: " + e.getMessage();
this.AcctNo = -1;
}
}
private void writestatus() { //should write status and write log be one method?
try {
PrintWriter out = new PrintWriter(
new FileWriter(this.typecd + this.AcctNo + ".txt"));
out.println(this.nm);
out.println(this.balance);
out.close();
} catch (IOException e) {
errmsg = "Error writing status file for "
+ this.typecd + " account: "+ this.AcctNo;
} catch(Exception e) {
errmsg = "General error in status update: " + e.getMessage();
}
} //end of writestatus

IN OR multiple operator SAP Java

I am creating a query using JCO, SAP util for the following code for example:
public static void TEST() throws JCoException {
JCoDestination destination;
JCoRepository sapRepository;
destination = JCoDestinationManager.getDestination(ABAP_AS);
JCoDestinationManager.getDestination(ABAP_AS);
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
try {
JCoContext.begin(destination);
sapRepository = destination.getRepository();
if (sapRepository == null) {
System.out.println("Couldn't get repository!");
System.exit(0);
}
JCoFunctionTemplate functionTemplate = sapRepository.getFunctionTemplate("EM_GET_NUMBER_OF_ENTRIES");
JCoFunction function = functionTemplate.getFunction();
JCoTable itTable = function.getTableParameterList().getTable("IT_TABLES");
itTable.appendRow();
itTable.setValue("TABNAME", "USR02");
// JCoTable returnOptions_ = function.getTableParameterList().getTable("OPTIONS");
// returnOptions_.appendRow();
//// //returnOptions.setValue("TEXT", "MODDA GE '20140908' AND MODTI GT '000000'");
// returnOptions_.setValue("TEXT", "BNAME EQ 'USER'");
function.execute(destination);
System.out.println( function.getTableParameterList().getTable("IT_TABLES").getInt("TABROWS"));
JCoFunctionTemplate template2 = sapRepository.getFunctionTemplate("RFC_READ_TABLE");
System.out.println("Getting template");
JCoFunction function2 = template2.getFunction();
function2.getImportParameterList().setValue("QUERY_TABLE", "USR02");
function2.getImportParameterList().setValue("DELIMITER", ",");
function2.getImportParameterList().setValue( "ROWCOUNT",5);
function2.getImportParameterList().setValue( "ROWSKIPS",5);
System.out.println("Setting OPTIONS");
// Date date = new Date(1410152400000L);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
// String dateString = formatter.format(date);
// String dt = dateString.substring(0, 8);
// String tm = dateString.substring(8);
// System.out.println("dt > " + dt + ", tm > " + tm);
JCoTable returnOptions = function2.getTableParameterList().getTable("OPTIONS");
returnOptions.appendRow();
//returnOptions.setValue("TEXT", "MODDA GE '20140908' AND MODTI GT '000000'");
returnOptions.setValue("TEXT", "BNAME LIKE 'S%'");
// returnOptions.appendRow();
// returnOptions.setValue("TEXT", "AND TYPE = 'DN'");
System.out.println("Setting FIELDS");
JCoTable returnFields = function2.getTableParameterList().getTable("FIELDS");
returnFields.appendRow();
returnFields.setValue("FIELDNAME", "BNAME");
returnFields.appendRow();
returnFields.setValue("FIELDNAME", "GLTGB");
returnFields.appendRow();
returnFields.setValue("FIELDNAME", "CLASS");
// returnFields.appendRow();
function2.execute(destination);
// JCoTable jcoTablef = function2.getTableParameterList().getTable("FIELDS");
JCoTable jcoTabled = function2.getTableParameterList().getTable("DATA");
int icodeOffSet = 0;
int icodeLength = 0;
int numRows = jcoTabled.getNumRows();
System.out.println("numRows > " + numRows);
for(int i=0; i<numRows; i++) {
jcoTabled.setRow(i);
System.out.println(jcoTabled.getRow());
String BNAME = "BNAE:" + jcoTabled.getString(0);
// String GLTGB = "GLTGB:" + jcoTabled.getString(2);
// String cls = "GLTGB:" + jcoTabled.getString(3);
System.out.println(BNAME + "..." );
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("ERROR: " + e.getMessage());
} finally {
JCoContext.end(destination);
}
}
static void createDestinationDataFile(String destinationName, Properties connectProperties)
{
File destCfg = new File(destinationName+".jcoDestination");
try
{
FileOutputStream fos = new FileOutputStream(destCfg, false);
connectProperties.store(fos, "for tests only !");
fos.close();
}
catch (Exception e)
{
throw new RuntimeException("Unable to create the destination files", e);
}
}
The previous code worked well when I used the EQ operator.
However, when I used the IN operator:
BNAME IN ('USER1','USER','USER3')
or
BNAME EQ 'USER1' OR BNAME EQ 'USER' OR BNAME EQ 'USER3'
It throws an exception: Unexpected dynamic condition
Are there any limitations to the condition size? Since I have 22 field in the IN condition and each value has a size of 10?
You need to specify a valid OpenSQL condition, you need to observe the rules for dynamic conditions and you need to ensure that the condition is properly split into lines of 72 characters. My guess would be that the last bit might have been an issue if you're specifying 22 conditions...

Trouble Writing to file in java

Hey im trying to write to a file but im getting an error on the line where it writes the line that goes into each line of a text file, cant figure it out any help would be greatly appreciated
The Writer Code
.
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
The Full Code
import java.io.*;
import java.util.*;
public class StudentMain {
/**
* #param args
*/
//array and sorting variables
public static studentConstructor[] stuArrayOrig = new studentConstructor[23];
private static studentConstructor[] stuArrayIdSort = new studentConstructor[23];
private static studentConstructor[] stuArrayNameSort = new studentConstructor[23];
private static int lineCount = 0;
private static int nElms = 0;
//writer
//studentConstructor variables
public static String fn; //First Name
public static String ln; //Last Name
public static String pn; //Preferred Name
public static int id; //Student Id Number
public static boolean ft;//Full-time Boolean
public static int phn; //Student Phone Number
public static boolean lj;//Loving java Boolean
public static String con;//Continuing
File idSort = new File("stuListSortID.txt");
public static void StuRead()
{
Scanner inFile = null;
try
{
inFile = new Scanner
(new FileReader("Res/students.txt"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
while (inFile.hasNextLine()){
inFile.useDelimiter(",|\\n"); //breaks the lines into single info
ln = inFile.next();
System.out.println(ln);
fn = inFile.next();
System.out.println(fn);
pn = inFile.next();
System.out.println(pn);
id = inFile.nextInt();
System.out.println(id);
ft = inFile.nextBoolean();
System.out.println(ft);
phn = inFile.nextInt();
System.out.println(phn);
lj = inFile.nextBoolean();
System.out.println(lj);
con = inFile.next();
System.out.println(con);
studentConstructor st = new studentConstructor(ln, fn, pn, id, ft, phn, lj, con);
stuArrayOrig[lineCount] = st;
inFile.nextLine();
System.out.println(stuArrayOrig[lineCount]);
lineCount++;
}
//setting info into other arrays
stuArrayIdSort = stuArrayOrig;
stuArrayNameSort = stuArrayOrig;
System.out.println("orig array length" + stuArrayOrig.length);
System.out.println("id array length" + stuArrayIdSort.length);
System.out.println("name array length" + stuArrayNameSort.length);
System.out.println("number of file lines" + lineCount);
inFile.close();
}
public static void stuIdSort()
{
studentConstructor temp;
boolean sorted = false;
while (sorted == false)
{ sorted=true;
for (int i=0; i<stuArrayIdSort.length-1 ; i++)
{
if(stuArrayIdSort[i].getStuId() > stuArrayIdSort[i+1].getStuId())
{
temp = stuArrayIdSort[i+1];
stuArrayIdSort[i+1] = stuArrayIdSort[i];
stuArrayIdSort[i] = temp;
sorted=false;
}
}
}
for(int i=0; i<stuArrayIdSort.length; i++)
{
int getSC = stuArrayIdSort[i].studentId;
System.out.println("number of swaps " + i+1 +" " +getSC);
}
}
//stuArrayIdSort[i].getStuLastName(),stuArrayIdSort[i].getStuFirstName(),stuArrayIdSort[i].getPrefName(),stuArrayIdSort[i].getStuId(),stuArrayIdSort[i].getFTime(),stuArrayIdSort[i].getPhoneNum(),stuArrayIdSort[i].getLovJava(),stuArrayIdSort[i].getCont()
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
}
public static void stuNameSort()
{
}
public static void stuNameWrire()
{
}
}
//lastName, firstName, perName, studentId, fulltime,
Ok, here is what you should do:
What's happening is that you are closing it before it can actually do anything. So, lets move your finally clause to the end of everything:
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
i++;
}
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
I'm not sure you understand how try...catch...finally works. Here's what you have:
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
>>>>>>> **try {writer.close();} catch (Exception ex) {}**
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
//bunch of stuff
writer.write(...);
>>>>>>> **writer.close();**
i++;
}
}
You close writer ONCE before you've even used it (finally block gets executed after the try block), and ONCE inside the loop. So, if somehow the code could make it past the writer.close() in the finally block, it would never make it through the loop more than once.
It is not necessary to close a BufferedWriter. The class makes sure to close it internally.
If you are using Java 7, you might want to consider using the "try-with-resources" syntax, which can simplify a correct implementation of file handling greatly in cases like this. Your original code had some issues, but even the accepted answer has some problems that I believe will result in a NullPointerException in the case where the file can't be opened (unverified).
I think you may also have some problems with your while loop boundary conditions also. I've changed the while loop to the more traditional for loop. Keep in mind that java array elements run from 0 to array.length - 1 inclusive.
public static void stuIDWrite() throws IOException
{
try (FileWriter writer = new FileWriter("Res/stuIDSorted.txt"))
{
for (int i = 0; i < stuArrayIdSort.length; ++i)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn = stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + "," + id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
}
}
}
You could also look at using the "enhanced for loop" syntax for the inner loop that may further streamline things.

Using the JGIT, how can I retrieve the line numbers of added/deleted lines

Assuming the following piece of code is committed to a Git repository:
int test(){
int a = 3;
int b = 4;
int c = a + b;
return c;
}
and is later updated to
int test(){
return 7;
}
I currently have a method which uses the JGit API in order to access the Git repository where the above are committed and outputs a string which is similar to the following:
int test(){
-int a = 3;
-int b = 4;
-int c = a + b;
-return c;
+return 7;
}
Now, my requirements have changed and would like to know the line numbers of the changed lines only. So I would want something like the following:
2 -int a = 3;
3 -int b = 4;
4 -int c = a + b;
5 -return c;
2 +return 7;
Basically, the same information that the GitHub application gives when an update is made.
Any help would be greatly appreciated :)
snippet of how the -/+ lines are computed:
String oldHash = "ee3e216ab5047748a22e9ec5ad3e92834704f0cc";
Git git = null;
try {
//the path where the repo is.
git = Git.open(new File("C:\\Users\\Administrator\\Documents\\GitHub\\Trial"));
} catch (IOException e1) {
e1.printStackTrace();
}
Repository repository = git.getRepository();
ObjectId old = null;
ObjectId head = null;
//a new reader to read objects from getObjectDatabase()
ObjectReader reader = repository.newObjectReader();
//Create a new parser.
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
List<DiffEntry> diffs = null;
try {
//parse a git repository string and return an ObjectId
old = repository.resolve(oldHash + "^{tree}");
head = repository.resolve("HEAD^{tree}");
//Reset this parser to walk through the given tree
oldTreeIter.reset(reader, old);
newTreeIter.reset(reader, head);
diffs = git.diff()//Returns a command object to execute a diff command
.setNewTree(newTreeIter)
.setOldTree(oldTreeIter)
.call();//returns a DiffEntry for each path which is different
} catch (RevisionSyntaxException | IOException | GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//DiffLineCountFilter d = new DiffLineCountFilter();
//out is the stream the formatter will write to
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Create a new formatter with a default level of context.
DiffFormatter df = new DiffFormatter(out);
//Set the repository the formatter can load object contents from.
df.setRepository(git.getRepository());
ArrayList<String> diffText = new ArrayList<String>();
//A DiffEntry is 'A value class representing a change to a file' therefore for each file you have a diff entry
for(DiffEntry diff : diffs)
{
try {
//Format a patch script for one file entry.
df.format(diff);
RawText r = new RawText(out.toByteArray());
r.getLineDelimiter();
diffText.add(out.toString());
out.reset();
} catch (IOException e) {
e.printStackTrace();
}
}
You need to do the difference between the A line indexes and B line indexes from the diff result:
int linesAdded = 0;
int linesDeleted = 0;
int filesChanged = 0;
try {
repo = new FileRepository(new File("repo/.git"));
RevWalk rw = new RevWalk(repo);
RevCommit commit = rw.parseCommit(repo.resolve("486817d67b")); // Any ref will work here (HEAD, a sha1, tag, branch)
RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
df.setRepository(repo);
df.setDiffComparator(RawTextComparator.DEFAULT);
df.setDetectRenames(true);
List<DiffEntry> diffs;
diffs = df.scan(parent.getTree(), commit.getTree());
filesChanged = diffs.size();
for (DiffEntry diff : diffs) {
for (Edit edit : df.toFileHeader(diff).toEditList()) {
linesDeleted += edit.getEndA() - edit.getBeginA();
linesAdded += edit.getEndB() - edit.getBeginB();
}
}
} catch (IOException e1) {
throw new RuntimeException(e1);
}
Just a tip for anyone who might have this problem. I did not manage to get the line numbers of the added and deleted lines but I did manage to get a string which contains only the added and deleted lines without the other lines which were not changed.
This was simply done by adding the line:
df.setContext(0);
in the snippet I provided above right before the line
df.format(diff);
I do it this way but I don't know if it is correct
public void linesChangeInFile(Git git, List<RevCommit> commits, String fileName, String pathRepository) {
try {
List<RevCommit> commitsComparer = new ArrayList<>();
List<String> linesChange = new ArrayList<>();
for (int i = 0; i < commits.size() - 1; i++) {
ObjectId commitIDOld = commits.get(i).getId();
if (Validador.isFileExistInCommit(commits.get(i), getRepository(), fileName)) {
if (i != commits.size() - 1 && !commitsComparer.contains(commits.get(i))) {
ObjectId commitIDNew = commits.get(i + 1);
commitsComparer.add(commits.get(i));
linesChange.add(diff(git, commitIDOld.getName(), commitIDNew.getName(), fileName));
}
try (final FileInputStream input = new FileInputStream(pathRepository + "\\" + fileName)) {
currentLines = IOUtils.readLines(input, "UTF-8").size();
}
}
}
Integer sumLinesAdd = 0;
Integer sumLinesDel = 0;
for (String lineChange : linesChange) {
String[] lChange = lineChange.split(";");
sumLinesAdd += Integer.parseInt(lChange[0]);
sumLinesDel += Integer.parseInt(lChange[1]);
}
System.out.println("Lines Add total:" + sumLinesAdd);
System.out.println("Lines Del total:" + sumLinesDel);
System.out.println("Total lines change:" + (sumLinesAdd + sumLinesDel));
} catch (RevisionSyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String diff(Git git, String commitIDOld, String commitIDNew, String fileName) {
int linesAdded = 0;
int linesDeleted = 0;
DiffFormatter df = null;
try {
AbstractTreeIterator oldTreeParser = prepareTreeParser(getRepository(), commitIDOld);
AbstractTreeIterator newTreeParser = prepareTreeParser(getRepository(), commitIDNew);
List<DiffEntry> diffs = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser)
.setPathFilter(PathFilter.create(fileName)).call();
df = new DiffFormatter(DisabledOutputStream.INSTANCE);
df.setRepository(getRepository());
df.setDiffComparator(RawTextComparator.DEFAULT);
df.setDetectRenames(true);
for (DiffEntry entry : diffs) {
// System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to:
// " + entry.getNewId());
// try (DiffFormatter formatter = new DiffFormatter(System.out)) {
// formatter.setContext(0);
// formatter.setRepository(repository);
// formatter.format(entry);
// }
for (Edit edit : df.toFileHeader(entry).toEditList()) {
linesDeleted += edit.getEndA() - edit.getBeginA();
linesAdded += edit.getEndB() - edit.getBeginB();
}
}
} catch (IOException | GitAPIException e) {
System.err.println("Error:" + e.getMessage());
}
return linesAdded + ";" + linesDeleted;
}

Categories

Resources