I have a really strange problem:
(from the main function):
try {
java.io.InputStream is = null;
if (args.length == 0) {
is =
ClassLoader.
getSystemClassLoader().getResourceAsStream("level_sets.txt");
} else {
is =
ClassLoader.getSystemClassLoader().getResourceAsStream(args[0]);
}
LineNumberReader reader = null;
reader = new LineNumberReader(new InputStreamReader(is));
LevelSetReader lsr = new LevelSetReader(reader);
List<String> keyAdderss = lsr.getKeyAdressMap();
for (int i = 0; i < keyAdderss.size(); i++) {
String add = keyAdderss.get(i);
File file = new File(add);
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
the progrem at first check if there is a single commandline paramete - if don't, go to our default file called: "level_set.txt"(in our bin) otherwise check the file there.
(The level_sets.txt file contein addresses to other txt files.)
After that call every address and analise those too...
The problem is that he can no find those files in linux...
He can find the level_sets.txt but not the other files...
I must mention that it works perfect in eclips!
We tried hundreds of way but failed...
In addition, when we deleted the if-else at the begining it worked!!!
like:
java.io.InputStream is = null;
is =
ClassLoader.
getSystemClassLoader().getResourceAsStream("level_sets.txt");
What to do?
Thanks! :)
Related
I have been trying to merge two files into new file and below code does it job. But after the merge i want to delete the old files. The code I am using to delete files just delete 1 file (file2) not the both of them.
public static void Filemerger() throws IOException
{
String resultPath = System.getProperty("java.io.tmpdir");
File result = new File(resultPath+"//NewFolder", "//file3.txt");
// PrintWriter object for file3.txt
PrintWriter pw = new PrintWriter(result);
// BufferedReader object for file1.txt
BufferedReader br = new BufferedReader(new FileReader(resultPath+"file1.txt"));
String line = br.readLine();
// loop to copy each line of
// file1.txt to file3.txt
while (line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
br = new BufferedReader(new FileReader(resultPath+"file2.txt"));
line = br.readLine();
// loop to copy each line of
// file2.txt to file3.txt
while(line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
// closing resources
br.close();
pw.close();
File dir = new File(resultPath);
FileFilter fileFilter1 = new WildcardFileFilter(new String[] {"file1.txt", "file2.txt"}, IOCase.SENSITIVE);
File[] fileList1 = dir.listFiles(fileFilter1);
for (int i = 0; i < fileList1.length; i++) {
if (fileList1[i].isFile()) {
File file1 = fileList1[i].getAbsoluteFile();
file1.delete();
}
}
}
I also try this code to delete the file1 as above code delete the file2:
Path fileToDeletePath = Paths.get(resultPath+"file1.txt");
Files.delete(fileToDeletePath);
but it throws an exception that Exception in thread "main" java.nio.file.FileSystemException: C:\Users\haya\AppData\Local\Temp\file1: The process cannot access the file because it is being used by another process.
Closing the streams as suggested in the comments will fix. However you are writing a lot of code which is hard to debug / fix later. Instead simplify to NIO calls and add try with resources handling to auto-close everything on the way:
String tmp = System.getProperty("java.io.tmpdir");
Path result = Path.of(tmp, "NewFolder", "file3.txt");
Path file1 = Path.of(tmp,"file1.txt");
Path file2 = Path.of(tmp,"file2.txt");
try(OutputStream output = Files.newOutputStream(result)) {
try(InputStream input = Files.newInputStream(file1)) {
input.transferTo(output);
}
try(InputStream input = Files.newInputStream(file2)) {
input.transferTo(output);
}
}
Files.deleteIfExists(file1);
Files.deleteIfExists(file2);
Im having a problem in checking if a file exists in Java. However the IF block seems to work , but the ELSE seems dont. see, when a file exist, it will prompt a box that says, 'File found.' which happens in my program whenever a file do exist, the problem is errors flood in my console when a file dont exist. Can somebody tell me what's the easier and shorter way of coding my problem? thanks ! here's my code
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
File f = new File(textField.getText());
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
{
JOptionPane.showMessageDialog(null, textField.getText()+" found" );
while ((sCurrentLine = br.readLine()) != null) {
textArea.append(sCurrentLine);
textArea.append(System.lineSeparator());
}
}
else
{
JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
The problem is with this line:
br = new BufferedReader(new FileReader(path+f));
You're appending a File to a String, which doesn't make sense. You should append a String to a String, in this case textField.getText()) appended to path.
This line will throw an exception if the file doesn't exist as per the documentation of FileReader:
Throws:
FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
This causes your program to reach the catch clause and print an exception stack trace. You should only call this line when f.exists() returns true:
if (f.exists())
{
br = new BufferedReader(new FileReader(path + textField.getText()));
...
}
Look at these lines of your code:
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
You are trying to open the file before checking whether it exists. So if the attempt to open it fails with a FileNotFoundException, the test is never reached.
String path = "C:\\Path\\To\File\\Directory\\";
String fileName = "NameOfFile.ext";
File f = new File(path, fileName);
if(f.exists()) {
//<code for file existing>
} else {
//<code for file not existing>
}
You have to instantiate the BufferedReader after checking the existence of the file.
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
File f = new File(path + textField.getText());
...
if (f.exists())
{
br = new BufferedReader(new FileReader(f.getAbsolutePath())); // or br = new BufferedReader(f);
...
public class comparee {
static int count=0;
public static void main(String[] args) throws IOException {
String a,b;
FileReader fi = new FileReader(new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\a.txt")); // new file
FileReader fii = new FileReader(new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\b.txt")); // new file
BufferedReader br =new BufferedReader(fi); //new
BufferedReader br1 =new BufferedReader(fii); //old
FileWriter fw = new FileWriter(new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\samnew.txt"));
int count = 0;
while((a=br.readLine()) != null)
{
while((b=br1.readLine()) != null)
{
if(!(a.equals(b)))
{
count++;
fw.write(a);
}
}
System.out.println(count);
}
}
}
Hi, I am trying to compare string from a.txt and b.txt by reading line by line.
I would like to write the line on samdata.txt which is not available in a.txt but available on b.txt. would appreciate any help :) thanks
P.S the above code logic is incorrect
Comparing files is a complex operation, because you normally would have to look ahead in both files in order to find the next matching lines.
Now, if you are absolutely(!) sure that b.txt contains all the lines from a.txt, in the same order as a.txt, but has extra lines inserted at various places, then the following might be ok.
BTW: Your variable names are confusing, so I'm renaming them and using try-with-resources to ensure the readers and the writer get closed.
File fileA = new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\a.txt");
File fileB = new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\b.txt");
File fileNew = new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\samnew.txt");
int count = 0;
try (Reader readerA = new BufferedReader(new FileReader(fileA));
Reader readerB = new BufferedReader(new FileReader(fileB));
PrintWriter writer = new PrintWriter(new FileWriter(fileNew))) {
// Read first line of each file
String lineA = readerA.readLine();
String lineB = readerB.readLine();
// Compare lines
while (lineA != null || lineB != null) {
if (lineB == null) {
// Oops! Found extra line in file A
lineA = readerA.readLine(); // Read next line from file A
} else if (lineA == null || ! lineA.equals(lineB)) {
// Found new line in file B
writer.println(lineB);
lineB = readerB.readLine(); // Read next line from file A
count++;
} else {
// Lines are equal, so read next line from both files
lineA = readerA.readLine();
lineB = readerB.readLine();
}
}
}
System.out.println(count);
Why don't you read b.txt into a list and then in your code check if each line you read in a.txt is available in the list (list.contains()).
i want use my java class on the hadoop hdfs, now i must rewrite my functions.
the problem is, if i use the InputStreamReader my app read wrong values.
here my code (so it's work, i want use the uncommented code part):
public static GeoTimeDataCenter[] readCentersArrayFromFile(int iteration) {
Properties pro = new Properties();
try {
pro.load(GeoTimeDataHelper.class.getResourceAsStream("/config.properties"));
} catch (Exception e) {
e.printStackTrace();
}
int k = Integer.parseInt(pro.getProperty("k"));
GeoTimeDataCenter[] Centers = new GeoTimeDataCenter[k];
BufferedReader br;
try {
//Path pt=new Path(pro.getProperty("seed.file")+(iteration-1));
//FileSystem fs = FileSystem.get(new Configuration());
//br=new BufferedReader(new InputStreamReader(fs.open(pt)));
br = new BufferedReader(new FileReader(pro.getProperty("seed.file")+(iteration-1)));
for(int i =0; i<Centers.length; i++){
String[] temp = null;
try{
temp = br.readLine().toString().split("\t");
Centers[i] = new GeoTimeDataCenter(Integer.parseInt(temp[0]),new LatLong(Double.parseDouble(temp[1]),Double.parseDouble(temp[2])),Long.parseLong(temp[3]));
}
catch(Exception e) {
temp = Seeding.randomSingleSeed().split("\t");
Centers[i] = new GeoTimeDataCenter(i,new LatLong(Double.parseDouble(temp[0]),Double.parseDouble(temp[1])),DateToLong(temp[2]));
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return Centers;
}
maybe someone know this problem?
best regards
i have found the problem. i have get a checksum exception. now i delete all .crc files from my input file. in this way i get no checksum exception and the buffered reader work fine (uncommented code part, upstairs).
I am really thankful for everyone who would read this and try to help me, the following is the code I am trying to write for a server class for a socket-programming project for college:
import java.io.*;
import java.net.*;
import java.io.File;
class Server{
public static void main (String[]args)throws IOException{
ServerSocket socket1 = new ServerSocket (8000);
while (true) {
Socket incoming = socket1.accept();
new newclass(incoming).start();
}
}
}
class newclass extends Thread implements Runnable {
Socket incoming;
public newclass(Socket incoming) {
this.incoming = incoming;
}
public void run() {
try {
byte x = 0;
String z;
String s = "HTTP 1.0 200 Document follows";
String s1 = "Bad request message";
BufferedReader input = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
PrintWriter output = new PrintWriter(incoming.getOutputStream(), true);
DataOutputStream sending = new DataOutputStream(incoming.getOutputStream());
File directory = new File("C:\\Documents and Settings\\Ahmed\\Desktop\\bla\\Server");
File[] files = directory.listFiles();
int x1 = files.length;
if ((x1 - 3) < 10) {
boolean done = false;
while (!done) {
String line = input.readLine();
System.out.println(line);
if (line.equals("BYE")) {
output.println("BYE");
done = true;
} else {
if (line.trim().substring(0, 3).equals("GET ")) {
if (line.equals("<javalogo.png> HTTP 1.0")) {
File f = new File("javalogo.png");
int size = (int) f.length();
if (f.exists() == true) {
output.println(s);
output.println(size);
output.println("javalogo1.png");
DataInputStream bytefile = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
while (bytefile.available() != 0) {
x = bytefile.readByte();
sending.write(x);
}
} else {
System.out.println("Getting file from main server");
Socket socket2 = new Socket("127.0.0.1", 8100);
BufferedReader bUsr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pOut = new PrintWriter(socket2.getOutputStream(), true);
BufferedReader bIn = new BufferedReader(new InputStreamReader(socket2.getInputStream()));
pOut.println("GET <javalogo.png> HTTP 1.0");
String rep = bIn.readLine();
if (rep.equals("HTTP 1.0 200 Document follows")) {
int len = Integer.parseInt(bIn.readLine());
String fname = bIn.readLine();
File f1 = new File(fname);
f1.createNewFile();
FileOutputStream fos = new FileOutputStream(f1);
DataInputStream dis = new DataInputStream(socket2.getInputStream());
for (int i = 0; i < len; i++) {
fos.write(dis.read());
}
fos.close();
} else if (rep.equals("File does not exist")) {
output.println("Sorry, but the file was neither found in the proxy server or the main server or the name is wrong.");
}
}
}
File f2 = new File("javalogo.png");
if (f2.exists() == true) {
int size = (int) f2.length();
output.println(s);
output.println(size);
output.println("javalogo.png");
DataInputStream bytefile = new DataInputStream(new BufferedInputStream(new FileInputStream(f2)));
while (bytefile.available() != 0) {
x = bytefile.readByte();
sending.write(x);
}
}
} else {
System.out.println(s1);
output.println(s1);
}
}
}
incoming.close();
}
output.println("Connecting to main server");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Now I don't understand why am I getting an error when I run the following client on it.
I get this really weird error where the buffered reader reads the first line from the user correctly but with the second one it gives me a null exception as if the client wrote null or something, I dont get it.
Here's the client code anyways, if anyone can help me I would be plenty thankful.
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket1 = new Socket("127.0.0.1", 8000);
BufferedReader bUsr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pOut = new PrintWriter(socket1.getOutputStream(), true);
BufferedReader bIn = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
String cmd;
String rep;
while (true) {
cmd = bUsr.readLine();
pOut.println(cmd);
System.out.println(rep = bIn.readLine());
if (cmd.equals("BYE") || cmd.equals("END"))
break;
else if (rep.equals("HTTP 1.0 200 Document follows")) {
int len = Integer.parseInt(bIn.readLine());
String fname = bIn.readLine();
File f = new File(fname);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
DataInputStream dis = new DataInputStream(socket1.getInputStream());
for (int i = 0; i < len; i++) {
fos.write(dis.read());
}
fos.close();
System.out.println("Success");
} else if (rep.equals("Connecting to main server")) {
Socket socket1 = new Socket("127.0.0.1", 8100);
BufferedReader bUsr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pOut = new PrintWriter(socket1.getOutputStream(), true);
BufferedReader bIn = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
String cmd;
String rep;
while (true) {
cmd = bUsr.readLine();
pOut.println(cmd);
System.out.println(rep = bIn.readLine());
if (cmd.equals("BYE") || cmd.equals("END"))
break;
else if (rep.equals("HTTP 1.0 200 Document follows")) {
int len = Integer.parseInt(bIn.readLine());
String fname = bIn.readLine();
File f = new File(fname);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
DataInputStream dis = new DataInputStream(socket1.getInputStream());
for (int i = 0; i < len; i++) {
fos.write(dis.read());
}
fos.close();
System.out.println("Success");
}
}
}
bIn.close();
pOut.close();
socket1.close();
}
}
This is the first time asking anything on this site, so if I did anything wrong I would be more than happy to change what I wrote.
By the way, the part in the server which states "getting file from main server" is a part where the server itself becomes a client for a main server, from where it gets the file and sends it to the client, I didn't add the main server code because it'd be too much code but basically it's the same as server without the if condition restricting it to 10 files in the directory only.
In general, when there is a NullPointerException either:
You have not instantiated your object
Your object has been destroyed (closed) and therefore does not exist
You have an invalid cast
Your code has overwritten your object pointer
You would need to examine your stack dump to see which of these is true.
From the Jav Docs the read can throw IOException if an I/O error occurs and IOException can give you the specified detail message. The error message string can later be retrieved by the Throwable.getMessage() method of class java.lang.Throwable.
Two points:
What does the IOException detail give you?
Since this is for your college course, try asking your classmates or TA for assistance
I'd be lying if I said I fully understand what your code is doing - But if you are getting null data when you are reading from a stream which you expect to contain data it could be that the output stream hasn't 'flushed' the data.
Make sure you call the flush() method on your Output streams after you have written to them
Ahemd, I see a number of potential errors and some actual bugs too in the classes as posted, but the code is too complicated for me to focus on the issue you are seeing. If you're still experiencing network bugs, try reducing the code and both client and server to the minimal possible to get communication going (send/read one line). If that doesn't work for you, post those classes and we'll be able to see the problems much more quickly than with the larger classes posted here.
Good luck.
If you are getting null from a BufferedReader.readLine() it means you have reached the end of input as it states in the javadoc for this method.
The best way to find your errors solution , is to see a trace. Without it I see more than one error in your code.
Regards.