I'm trying to print '1' or '0' in text view if it passes the if statements. I ran it in the debug mode, and it all works, but it is not printing in the text view. How do I fix this I tried a lot of stuff, but I'm still stuck.
public class Readcsv {
private static final String FILE_DIR = "/Users/Me/Downloads";
private static final String FILE_TEXT_NAME = ".csv";
public static void main(String [] args) throws Exception{
PrintWriter writer = new PrintWriter("/users/Me/Documents/Test.txt", "UTF-8");
int i=-1;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
//Find Number of Files
String[] list = new Readcsv().FileCount(FILE_DIR, FILE_TEXT_NAME);
System.out.println("Total Files = " + list.length);
while(i++ < list.length){
System.out.println("Loop Count = " + i);
try {
br = new BufferedReader(new FileReader("/users/Tanuj/Downloads/" + list[i]));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] strRecord = line.split(cvsSplitBy);
if (!strRecord[0].equals("timestampMs")){
int c = Integer.parseInt(strRecord[4]);
int e = Integer.parseInt(strRecord[5]);
if(c>e){
writer.print("1");
}
else{
writer.print("0");
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} //End of while
writer.close();
} //End of Main
public String[] FileCount(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
if(dir.isDirectory()==false){
System.out.println("Directory does not exists : " + FILE_DIR);
return null;
}
// list out all the file name and filter by the extension
String[] list = dir.list((FilenameFilter) filter);
return list;
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
have you tryed BufferedWriter?
File file = new File("Test.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("something");
bw.newLine();
bw.close();
Related
I want to read out a file on a seperate thread and after that I want to move the file to a new directory but the compiler keeps telling me that I can't move the file because it is used by another process. I have checked it multiple times and my readers are closed and I used the join() function to wait until the readThread has finished what could this be?
public class CallLogReader extends Thread {
private Path path;
private LinkedList<CallLog> callLogs;
public CallLogReader(Path path){
setPath(path);
callLogs = new LinkedList<>();
}
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public LinkedList<CallLog> getCallLogs() {
return callLogs;
}
#Override
public void run(){
FileReader reader = null;
BufferedReader buffReader = null;
try{
reader = new FileReader(path.toFile());
buffReader = new BufferedReader(reader);
String currentLine = buffReader.readLine();
while(currentLine != null){
String[] dataBlocks = currentLine.split(";");
if(!dataBlocks[7].equals("IGNORE")){
callLogs.add(new CallLog(Integer.parseInt(dataBlocks[0]) ,dataBlocks[1], ConvertStringToDate(dataBlocks[2], dataBlocks[3]), dataBlocks[4], dataBlocks[5], Integer.parseInt(dataBlocks[6]), dataBlocks[7]));
}
currentLine = buffReader.readLine();
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
try{
if(buffReader != null){
buffReader.close();
}
if(reader != null){
reader.close();
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}
private LocalDateTime ConvertStringToDate(String dateString,String timeString){
String dateTimeString = dateString + " " + timeString;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
return LocalDateTime.parse(dateTimeString,formatter);
}
public void moveFile(){
Path newPath = Paths.get(path.getParent().getParent().toString() + "\\processed\\" + path.getFileName());
try{
Files.move(path,newPath,StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Path path_1 = Paths.get("C:\\Users\\11601037\\Desktop\\resources\\in\\testdata1.csv");
CallLogReader reader_1 = new CallLogReader(path_1);
reader_1.run();
try{
reader_1.join();
}
catch(InterruptedException ex){
System.out.println(ex.getMessage());;
}
reader_1.moveFile();
System.out.println(path_1.getParent().getParent().toString());
}
}
Just wondering what I have done wrong here I'm getting an error in the method setLine() which is:
error: incompatible types: String[] cannot be converted to State[]
Im not too sure on what to do to fix it since I need the line to be split and stored in that state array so I can determine whether if it is a state or location when reading from a csv file.
public static void readFile(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int stateCount = 0, locationCount = 0;
String line;
try
{
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
if (line.startsWith("STATE"))
{
stateCount++;
}
else if (line.startsWith("LOCATION"))
{
locationCount++;
}
line = bufRdr.readLine();
}
fileStrm.close();
State[] state = new State[stateCount];
Location[] location = new Location[locationCount];
}
catch (IOException e)
{
if (fileStrm != null)
{
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
public static void processLine(String csvRow)
{
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ":");
while (strTok.hasMoreTokens())
{
thisToken = strTok.nextToken();
System.out.print(thisToken + " ");
}
System.out.println("");
}
public static void setLine(State[] state, Location[] location, int stateCount, int locationCount, String line)
{
int i;
state = new State[stateCount];
state = line.split("="); <--- ERROR
for( i = 0; i < stateCount; i++)
{
}
}
public static void writeOneRow(String inFilename)
{
FileOutputStream fileStrm = null;
PrintWriter pw;
try
{
fileStrm = new FileOutputStream(inFilename);
pw = new PrintWriter(fileStrm);
pw.println();
pw.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch (IOException ex2)
{}
}
System.out.println("Error in writing to file: " + e.getMessage());
}
}
This error occurs, as it just says 'String[] cannot be converted to State[]'. That is like you wanted to store an Integer into a String, it's the same, because the types don't have a relation to each other (parent -> child).
So if you want to solve your problem you need a method which converts the String[] into a State[]. Something like this:
private State[] toStateArray(String[] strings){
final State[] states = new State[strings.length];
for(int i = strings.length-1; i >= 0; i--){
states[i] = new State(strings[i]); // here you have to decide how to convert String to State
}
return states;
}
So i have made two methods that creates the file (createFile(); and one to fill the textfile with empty highscores if none are set.
public class HighscoreList {
static String highscore = null;
static PuzzleModel theModel;
static File file = null;
public static int nom;
public static int tu;
public static int nor;
public static String search = " ";
static String replace = "2";
static String numberOfRows = null;
static String timeUsed = " ";
static String numberOfMoves = " ";
public static void main(String[] args) {
createFile();
isEmptySetEmptyHighscore();
// checkScore(0);
getHighscore(0);
}
public static void createFile() {
file = new File("C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt");
System.out.println("Created file " + file.getName());
if (!file.exists()) {
System.out.println("File didn't exist creating new file");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void isEmptySetEmptyHighscore() {
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if (br.readLine() == null) {
setEmptyHighscoreFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setEmptyHighscoreFile() {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("File is empty, fills with empty fields");
for (int i = 3; i < 101; i++) {
bw.write(i + ":" + numberOfMoves + ":" + timeUsed+"\n");
}
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
I have a getHighscore() that reads the two empty " " fields with moves and timeUsed. It is currently able to read this, but i cant write to those empty spaces in the textfile and replace them with actual numbers that i want.
EDIT: With the replace command it just adds it to the bottom of the file.
Is there something wrong with my code that re erases the text that i try to replace or how do i do it?
I tried something like this:
public static void writeToFile(int rows) {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if(br.readLine().split(":")[0].equals(Integer.toString(rows+1))){
bw.write(br.readLine().replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
have you try this ?
String line = br.readLine();
if(line.split(":")[0].equals(Integer.toString(rows+1))){
bw.write(line.replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}
I have a folder called attachment which contains 5 .gif images and i have a att.txt which contains name for this .gif images, Now i need to rename these images with the name present in att.txt.
Below is the code i tried.Please help
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader br = new java.io.BufferedReader(new FileReader("D:\\template_export\\template\\attachments"));
String sCurrentLine="";
while ((sCurrentLine = br.readLine()) != null) {
sCurrentLine= sCurrentLine.replaceAll("txt", "gif");
String[] s = sCurrentLine.split(",");
for(int i=0;i<s.length;i++){
new File("D:\\template_export\\template\\attachment_new"+s[i]).mkdirs();
System.out.println("Folder Created");
}
}
}
Try this:
public class Tst {
public static void main(String[] args) {
File orgDirectory = new File("attachements");// replace this filename
// with the path to the folder
// that contains the original images
String fileContent = "";
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachements.txt")))) {
for (String line; (line = br.readLine()) != null;) {
fileContent += line;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] newLocations = fileContent.split(" ");
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
File destinationFolder = new File("processed");
int max = Math.min(orgFiles.length, newLocations.length);
for (int i = 0; i < max; i++) {
String newLocation = newLocations[i];
int lastIndex = newLocation.lastIndexOf("/");
if (lastIndex == -1) {
continue;
}
String newDirName = newLocation.substring(0, lastIndex);
String newName = newLocation.substring(lastIndex);
File newDir = new File(destinationFolder, newDirName);
if (!newDir.exists()) {
newDir.mkdir();
}
try {
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It probably won't work since your description isn't that clear but I hope you get the idea and you understand how this task can be done. The important parts are:
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
Which creates a File array which contains all the "gif" files in the source directory.
And:
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
Which mover the original image to the new directory and sets its name to the one retrieved from the "attachements.txt" file.
my text
is like that
SEHiR;iL;iLCE;Tip;22356
S SI n;ISTA;ANK;A:S;22356
K K n;IS:TA;BB;B:S;22356
A A b;IS.TA;CC;DK;22356
G S b;ISTA;DD;O:P;22356
I want to change TIP column. I want to put "." instead of ":" for only Tıp column which include A:S,B:S etc.. And I want to write line before changing and after changing to csv. How can I do that? I write something but it has problem at
if(eD.tip.contains(":")) part because it dont continue to hS.Add(eD)
endeks.put("", hS); ı don’t want use “” string.
I do not have to use HasMap I could not write output what I want..
ı expected this output
S SI n;ISTA;ANK;A:S;22356
S SI n;ISTA;ANK;A.S;22356
K K n;IS:TA;BB;B:S;22356
K K n;IS:TA;BB;B.S;22356
G S b;ISTA;DD;O:P;22356
G S b;ISTA;DD;O.P;22356
public class MaliyeVknmDegil {
static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
static HashMap<String,HashSet<EndeksDegeri>> endeks = new HashMap<String, HashSet<EndeksDegeri>>();
static PrintWriter pW;
static EndeksDegeri eD = new EndeksDegeri();
static String satır;
private static PrintWriter pW2;
public static void main(String[] args) {
FileInputStream fIS;
FileOutputStream fOS;
try {
fIS = new FileInputStream("C:\\deneme\\DENEME.csv");
Reader r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
fOS = new FileOutputStream("c:\\yazdirilan\\deneme.csv");
Writer w = new OutputStreamWriter(fOS, "UTF-8");
pW2 = (new PrintWriter(w));
String satır;
String[] eleman;
while ((satır = bR.readLine()) != null) {
eleman = satır.split(";");
if(satır.contains(":")){
pW2.write(satır);
}
HashSet<EndeksDegeri> hS = new HashSet<EndeksDegeri>();
for (int i = 0; i < eleman.length; i++) {
// alteleman=eleman[i].split(" ");
EndeksDegeri eD = new EndeksDegeri();
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
if(eD.tip.contains(":")){
eD.tip.replaceAll(":", ".");
eD.tip = eleman[3];
}
eD.numara = Integer.parseInt(eleman[4]);
hS.add(eD);
}
endeks.put("", hS);
}
bR.close();
// yazdir
HashSet<EndeksDegeri> hS;
for (String s : endeks.keySet()) {
hS = endeks.get(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}// main end
}// clas end
package stackoverflow;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
public class TipChange {
private static String inputPath = "input.csv";
private static String outputPath = "output.csv";
private static BufferedReader bufferedReader;
private static PrintWriter printWriter;
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream(inputPath);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(reader);
FileOutputStream outputStream = new FileOutputStream(outputPath);
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
printWriter = new PrintWriter(writer);
String line;
while ((line = bufferedReader.readLine()) != null) {
EndeksDegeri eD = lineToClass(line);
if (shouldOutput(eD)) {
printWriter.append(classToLine(eD, true));
printWriter.append(classToLine(eD, false));
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean shouldOutput(EndeksDegeri eD) {
if (!eD.tip.contains(":")) {
return false;
}
return true;
}
private static String classToLine(EndeksDegeri eD, boolean original) {
if (!original) {
eD.tip = eD.tip.replace(":", ".");
}
return eD.sirket.concat(";")
.concat(eD.sehir).concat(";")
.concat(eD.ilce).concat(";")
.concat(eD.tip).concat(";")
.concat(String.valueOf(eD.numara)
.concat("\r\n"));
}
private static EndeksDegeri lineToClass(String line) {
String[] element = line.split(";");
EndeksDegeri endeksDegeri = new EndeksDegeri();
endeksDegeri.sirket = element[0];
endeksDegeri.sehir = element[1];
endeksDegeri.ilce = element[2];
endeksDegeri.tip = element[3];
endeksDegeri.numara = Integer.valueOf(element[4]);
return endeksDegeri;
}
private static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
}
Sample input:
SSI;ISTA;ANK;A:S;22356
KK;IS:TA;BB;B:S;22356
AA;IS.TA;CC;DK;22356
GS;ISTA;DD;O:P;22356
Generated Output:
SSI;ISTA;ANK;A:S;22356
SSI;ISTA;ANK;A.S;22356
KK;IS:TA;BB;B:S;22356
KK;IS:TA;BB;B.S;22356
GS;ISTA;DD;O:P;22356
GS;ISTA;DD;O.P;22356
Your code will produce a NullPointerException in the line: if(eD.tip.contains(":")){
That is because when a new EndeksDegeri instance is created all its fields are null you cannot call contains() on a null string.
Check the example code below (It writes to the console but it should get you going)
static class EndeksDegeri {
String sirket;
String sehir;
String ilce;
String tip;
int numara;
// I have added this method for convenience to write to the output
public String toString() {
return sirket + ":" + sehir + ":" + ilce + ":" + tip + ":" + numara;
}
}
while ((satir = bR.readLine()) != null) {
eleman = satir.split(";");
boolean found = false;
EndeksDegeri eD = new EndeksDegeri();
// first set all fields to not get exception
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
eD.tip = eleman[3];
eD.numara = Integer.parseInt(eleman[4]);
// check if the line contains ":"
if (eD.tip.contains(":")) {
// If yes, write the original line first
System.out.println(eD.toString());
// Change the record
eD.tip = eD.tip.replaceAll(":", ".");
found = true;
}
if (found) {
// write the corrected line now
System.out.println(eD.toString());
}
}
// Will print only the lines with ":" and its correct version
SSI:ISTA:ANK:A:S:22356
SSI:ISTA:ANK:A.S:22356
KK:IS:TA:BB:B:S:22356
KK:IS:TA:BB:B.S:22356
GS:ISTA:DD:O:P:22356
GS:ISTA:DD:O.P:22356