Read File

I am a trying to write a program to read from a text file that is continuously getting longer. I wrote it in C++ originally and it works fine. Now I am trying to write the same program in Java. Since I am a beginner at java I was wondering if someone could help me "translate" my code. I was not sure if this is the right place to ask this question, if I have made a mistake please advise me on where to put this question.

Here is my code in C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

//reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
	char line[81];
	streamsize ssize;
	streamsize len=80;
	ifstream myfile ("test.txt",ifstream::in);
	if (myfile.good())
	{
		while ( myfile.good() )
		{
			memset(line,0,len);
			ssize=myfile.readsome(line,len)
			//getline (myfile,line);
			if (ssize>0)
			{
				cout.write (line, ssize); 
			}
		}
		myfile.close();
	}
	else
	{
		cout << "Unable to open file";
	}
	return 0;
}
I'm probably more of a beginner to Java then you but I can tell you that the reason that you are having trouble with this is that you are using native C\C++ methods instead of those exported by a dll. Would it be good enough to call this program from the Java shell? That would certainly simplify things.
It would better for you to just track down an example of how to read a file in Java and compare the two.

If you're just learning Java, try this forum:
http://www.java-forums.org/new-java/

Andy

P.S. The second hit -- when I Googled "how to read a file in java" -- was:
http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html

(I'm not sure, but I think you can read files in a more basic way, but here the code is using a buffered stream. Which is what an istream is in the C++ world.)
Last edited on
Topic archived. No new replies allowed.