String Tokenizing error occurs - java

there is a text file which we read from it , then we want to write it after some little changes to othere text file, but the question is that why it has different results if we use
System.out.println and when we use pwPaperAuthor.println?
the code is like :
package cn.com.author;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
//input:"IndexAuthors1997-2010.txt"
//output:"PaperAuthor1997-2010.txt"
public class PaperAuthors {
public static void main(String[] args) {
BufferedReader brIndexAuthors = null;
BufferedWriter bw = null;
PrintWriter pwPaperAuthor = null;
try {
brIndexAuthors = new BufferedReader(new InputStreamReader(
new FileInputStream("IndexAuthors1997-2010.txt")));
bw = new BufferedWriter(new FileWriter(new File(
"PaperAuthor1997-2010.txt")));
pwPaperAuthor = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("PaperAuthor1997-2010.txt")));
/*
* line = brIndexAuthors.readLine();
*
* element=line.split("#"); String author=null; StringTokenizer st =
* new StringTokenizer(element[1],","); while(st.hasMoreTokens()) {
* author = st.nextToken(); pwPaperAuthor.println(element[0] + "+" +
* author); //~i++; }
*/
String line = null;
String element[] = new String[3];
String author = null;
int i = 0;
while ((line = brIndexAuthors.readLine()) != null) {
element = line.split("##");
StringTokenizer st = new StringTokenizer(element[1], ",");
int num=st.countTokens();
while (st.hasMoreTokens()) {
author = st.nextToken();
pwPaperAuthor.println(element[0]+"#"+author+"#"+element[2]);
bw.write(element[0] + "#" + author + "#" + element[2]);
bw.newLine();
System.out.println(element[0]+"#"+author+"#"+element[2]);
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
Ouput
if
System.out.println(element[0]+"#"+author+"#"+element[2]);------>620850#Henk Ern
if
pwPaperAuthor.println(element[0]+"#"+author+"#"+element[2]);
----->620850#Henk Ernstblock#2001

There's no way you can read a file and write to it in the same loop, using the stream-based API. You will have to create a new file and copy everything that's the same, adding what's new. What you are doing now has unpredictable behavior. If you still want to read and write at the same time, you'll have to use the RandomAccessFile, but that's quite a bit more complicated.

Related

Remove line from text file if it contains string java

I want to do read from text file, if I find certain email then I want to remove the entire line.
So I want to remove email555#email.com
stuffherestuffemail555#email.comstuffstuff
otherrandomwordsinrandomorder
reandom word and spaces maybe # and charcters email555#email.com
APPLEPEARAPPLE
CATDOGCAT
CATDOGPEARemail555#email.comDogPear
To this
otherrandomwordsinrandomorder
APPLEPEARAPPLE
CATDOGCAT
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class SendReq {
public static void main(String[] args) throws FileNotFoundException,
IOException{
File inputFile = new File("testfile.txt");
if (!inputFile.exists()){
inputFile.createNewFile();
}
File tempFile = new File("tempfile.txt");
if (!tempFile.exists()){
tempFile.createNewFile();
}
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "NAMEOFEMAIL#EMAIL.com";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}

How to insert a graph dataset into Orientdb database?

I created a OrientDB database using Java. Now I need to insert a dataset (a text file). I need help for this.
An example of file which i need to insert into my database.
My current code:
package creationdbgraph;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CreationDbGraph {
public static void main(String[] args)throws FileNotFoundException, IOException {
String nameDb="Graph";
String currentPath="remote:localhost/"+nameDb;
OServerAdmin serverAdmin;
try {
serverAdmin = new OServerAdmin(currentPath).connect("root", "19952916");
if(!serverAdmin.existsDatabase()){
serverAdmin.createDatabase(nameDb, "graph", "plocal");
OrientGraphNoTx g = new OrientGraphNoTx(currentPath);
OClass FromNode=g.createVertexType("FromNode", "V");
FromNode.createProperty("ID", OType.STRING);
OClass ToNode=g.createVertexType("ToNode", "V");
ToNode.createProperty("ID", OType.STRING);
g.createEdgeType("Edge", "E");
g.shutdown();
OrientGraph g1 = new OrientGraph(currentPath);
File file = new File("C:\\Users\\USER\\Downloads\\orientdb-community-2.2.20\\dataset.txt");
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNext()) {
OrientVertex node1=g1.addVertex("class:FromNode");
OrientVertex node2=g1.addVertex("class:ToNode");
if(scanner.hasNextInt())
{
node1.setProperty("ID",scanner.nextInt());
continue;
}
node2.setProperty("ID",scanner.nextInt());
node1.addEdge("Edge", node2);
}
}
System.out.println(list);
g1.shutdown();
}
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Your case is pretty simple, if the file is not huge (< millions of rows) you can use the graph batch insert: http://orientdb.com/docs/2.2.x/Graph-Batch-Insert.html

update a csv file after 1 hour in java

I have made a thread in java which continuously checks the recent items in the windows after a time interval of 1 hour and make a .csv file of all of the recent items. Moreover i have accesstime and folder location of all of the files in the recent items. Now what i am trying to do is as recent items continuously update itself so if there is a new file in the recent item it should append at the end of that already made csv file but i am stuck here and have no idea how to do that kindly help me My code is here
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package record;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import static java.sql.DriverManager.println;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.awt.shell.ShellFolder;
/**
*
* #author zeeshan
*/
public class Record
{
static String user=System.getProperty("user.name");
static String path1="C:\\Users\\"+user+"\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\";
static String path2="C:\\Users\\Fa16Rcs028\\Dropbox\\Spring 17\\Special Topics In HCI\\Sir Aimal Project\\output.csv";
static PrintWriter pw;
static StringBuilder sb = new StringBuilder();
public void createcsv()throws IOException
{
File directory = new File(path1);
File[] fList = directory.listFiles();
pw = new PrintWriter(new File(path2));
sb.append("File/Folder Name");
sb.append(',');
sb.append("Access Time");
sb.append(',');
sb.append("File Location");
sb.append('\n');
for (int i=0;i<fList.length;i++)
{
String filename=fList[i].getName();
String actualfilename=filename.replace(".lnk", "");
ShellFolder sf = ShellFolder.getShellFolder(fList[i]);
ShellFolder target = sf.getLinkLocation();
if (target != null)
{
Path p = Paths.get(path1+filename);
BasicFileAttributes view= Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
FileTime fileTime=view.creationTime();
sb.append(actualfilename);
sb.append(',');
sb.append(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format((fileTime.toMillis())));
sb.append(',');
sb.append(target.getAbsolutePath());
sb.append('\n');
}
}
pw.write(sb.toString());
pw.close();
}
public static class maintainrecord extends Thread
{
#Override
public void run()
{
File directory = new File(path1);
File[] fList = directory.listFiles();
for (File fList1 : fList) {
try {
String filename = fList1.getName();
String actualfilename=filename.replace(".lnk", "");
Path p = Paths.get(path1+filename);
BasicFileAttributes view= Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
FileTime fileTime=view.creationTime();
String time=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format((fileTime.toMillis())).toString();
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(path2)))
{
while ((line = br.readLine()) != null)
{
String[] record = line.split(cvsSplitBy);
String name=record[0];
String checktime=record[1];
if(actualfilename.equals(name) && !time.equals(checktime))
{
br.close();
pw = new PrintWriter(new File(path2));
sb.append(actualfilename);
sb.append(',');
sb.append(actualfilename);
sb.append(',');
}
}
}
}catch (IOException ex)
{
Logger.getLogger(Record.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String[] args) throws IOException
{
Record r=new Record();
r.createcsv();
Thread zeeshan=new Thread(new maintainrecord());
zeeshan.start();
Thread.sleep(600000);
}
}

How to delete a line from a text file based on certain criteria

Just wondering if anyone would know how to iterate through a csv file and based on a set of rules, delete various lines. Or, alternatively the lines that satisfy the rules can be added to a new output.csv file.
So far I have managed to read the csv file and add each line to an ArrayList. But now I need to apply a set of rules to these lines (preferably using an if statement) and delete lines that do not fit the criteria.
package codeTest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
String filename = "sample.csv";
try(Stream<String> stream = Files.lines(Paths.get(filename))){
stream.forEach(System.out::println);
try {
File inputFile = new File("sample.csv");
File outputFile = new File("Output.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String strLine;
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
while((strLine = reader.readLine()) != null){
list.add(strLine);
}
System.out.println("\nTEST OUTPUT..........................\n");
Stream<String> lineToRemove = list.stream().filter(x -> x.contains("yes"));
} catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
}
Any suggestions?
I am in complete coders block if there is such a thing.
You can use Files.write method:
List<String> filtered = Files.lines(Paths.get(filename)).
filter(x -> x.contains("yes")).collect(Collectors.toList());
Files.write(Paths.get("Output.txt"),filtered);

Jar ignoring all methods

I was making a pretty simple jar to unzip a zip and run the jar that was inside of it. The problem I've run into is that it doesn't do anything at all.
This is the main, and only class file for the jar. The manifest does point correctly to it, and it loads without errors.
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
import java.net.URLConnection;
import java.net.URL;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.Enumeration;
import sign.signlink;
import java.nio.file.*;
import java.io.FileReader;
public class ClientUpdater {
private String fileToExtractNew = "/client.zip";
private String getJarDir() throws FileNotFoundException, IOException{
String linebuf="",verStr="";
FileInputStream fis = new FileInputStream("/runLocationURL.txt");
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
while ((linebuf = br.readLine()) != null) {
verStr = linebuf;
}
return verStr;
}
public static void main(String[] args) {
System.out.println("start");
}
private void unZip() {
System.out.println("unzipping");
try {
ZipEntry zipEntry;
//client
BufferedInputStream bufferedInputStreamNew = new BufferedInputStream(new FileInputStream(this.fileToExtractNew));
ZipInputStream zipInputStreamNew = new ZipInputStream(bufferedInputStreamNew);
//client
while ((zipEntry = zipInputStreamNew.getNextEntry()) != null) {
String stringNew = zipEntry.getName();
File fileNew = new File(this.getJarDir() + File.separator + stringNew);
if (zipEntry.isDirectory()) {
new File(this.getJarDir() + zipEntry.getName()).mkdirs();
continue;
}
if (zipEntry.getName().equals(this.fileToExtractNew)) {
this.unzipNew(zipInputStreamNew, this.fileToExtractNew);
break;
}
new File(fileNew.getParent()).mkdirs();
this.unzipNew(zipInputStreamNew, this.getJarDir() + zipEntry.getName());
}
zipInputStreamNew.close();
}
catch (Exception var1_2) {
var1_2.printStackTrace();
}
}
private void unzipNew(ZipInputStream zipInputStreamNew, String stringNew) throws IOException {
System.out.println("unzipping new");
FileOutputStream fileOutputStreamNew = new FileOutputStream(stringNew);
byte[] arrby = new byte[4024];
int n = 0;
while ((n = zipInputStreamNew.read(arrby)) != -1) {
fileOutputStreamNew.write(arrby, 0, n);
}
fileOutputStreamNew.close();
Runtime.getRuntime().exec("java -jar " + getJarDir() + "/Project Pk Client.jar");
System.exit(0);
}
}
It shows the "Start" message, but not the other 2, so it never reaches those methods. Is it because they aren't being called? I'm still learning Java.
You actually have to call your other methods from main. Right now, all you are telling the computer to do is print start and then exit. Functions do not get called simply by existing.
It seems based on a quick glance that you just need to add unzip(); to your main function, right after the System.out.println line.
To do this, you need to say that those other methods are static, so you need to say private static void unZip() instead of private void unZip(). Do this for your other methods too.
import java.io.*;
import static java.lang.Integer.parseInt;
import java.net.URLConnection;
import java.net.URL;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.Enumeration;
import sign.signlink;
import java.nio.file.*;
public class ClientUpdater {
private String fileToExtractNew = "/client.zip";
private static String getJarDir() throws FileNotFoundException, IOException{
String linebuf="",verStr="";
FileInputStream fis = new FileInputStream("/runLocationURL.txt");
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
while ((linebuf = br.readLine()) != null) {
verStr = linebuf;
}
return verStr;
}
public static void main(String[] args) {
System.out.println("start");
unZip();
}
private static void unZip() {
System.out.println("unzipping");
try {
ZipEntry zipEntry;
//client
BufferedInputStream bufferedInputStreamNew = new BufferedInputStream(new FileInputStream(this.fileToExtractNew));
ZipInputStream zipInputStreamNew = new ZipInputStream(bufferedInputStreamNew);
//client
while ((zipEntry = zipInputStreamNew.getNextEntry()) != null) {
String stringNew = zipEntry.getName();
File fileNew = new File(this.getJarDir() + File.separator + stringNew);
if (zipEntry.isDirectory()) {
new File(this.getJarDir() + zipEntry.getName()).mkdirs();
continue;
}
if (zipEntry.getName().equals(this.fileToExtractNew)) {
this.unzipNew(zipInputStreamNew, this.fileToExtractNew);
break;
}
new File(fileNew.getParent()).mkdirs();
this.unzipNew(zipInputStreamNew, this.getJarDir() + zipEntry.getName());
}
zipInputStreamNew.close();
}
catch (Exception var1_2) {
var1_2.printStackTrace();
}
}
private static void unzipNew(ZipInputStream zipInputStreamNew, String stringNew) throws IOException {
System.out.println("unzipping new");
FileOutputStream fileOutputStreamNew = new FileOutputStream(stringNew);
byte[] arrby = new byte[4024];
int n = 0;
while ((n = zipInputStreamNew.read(arrby)) != -1) {
fileOutputStreamNew.write(arrby, 0, n);
}
fileOutputStreamNew.close();
Runtime.getRuntime().exec("java -jar " + getJarDir() + "/Project Pk Client.jar");
System.exit(0);
}
}

Categories