I'm supposed to send packets of a file over to a server which then prints it out. The problem i have is that it prints out only every odd number (0-nothing, 1- text, 2- nothing, 4-text etc..). This gets done in the server class. Can anyone see what he problem is?
Client
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Client myCli = new Client();
myCli.run();
}
public void run() throws Exception {
Socket mySkt = new Socket("localhost", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
BufferedReader in = new BufferedReader(new FileReader("C:/Users/Thormode/Dropbox/Skole 2013-2014/java/da/src/da/tekst.txt"));
while (in.ready()) {
String s = in.readLine();
myPS.println(s);
}
in.close();
//BufferedReader myBR = new BufferedReader(new InputStreamReader(mySkt.getInputStream()));
//String temp = myBR.readLine();
//System.out.println(temp);
mySkt.close();
myPS.close();
}
}
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception {
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
BufferedReader SS_BF = new BufferedReader(new InputStreamReader(
SS_accept.getInputStream()));
int i = 0;
String[] array = new String[10];
while (SS_BF.readLine() != null) {
array[i] = SS_BF.readLine();
i++;
}
for (int j = 0; j < i; j++) {
String temp = array[j];
System.out.println(temp);
}
SS_accept.close();
mySS.close();
}
}
while (SS_BF.readLine() != null) {
array[i] = SS_BF.readLine();
i++;
}
You are calling SS_BF.readLine twice. It discards the first line because of this.
while ((String line = SS_BF.readLine()) != null) {
array[i] = line;
i++;
}
The following code will read two lines a loop:
String[] array = new String[10];
while (SS_BF.readLine() != null) { // reads a line and forgets it's value
array[i] = SS_BF.readLine(); // reads every second line and puts it into the array
i++;
}
So you have to do it like this:
String[] array = new String[10];
String line = SS_BF.readLine(); // read first line and store it to 'line'
while (line != null) {
array[i++] = line; // set 'line' to array
line = SS_BF.readLine(); // read next line
}
Related
Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123
I explain my program. This program have two files and two files have student no, student name and surname.
Example:
queues.txt :
Student_No#Name#Surname
1234#Jane#Weber#
1235#Johnson#Roy
1267#Henry#Morin
stack.txt:
Student_No#Name#Surname
3456#Jane#lee
7535#Johnson#Perez
1967#Henry#Fortin
How do I read and throw stack and queue?
Program has Data class , Node class , Stack class , Queue Class and Main Class.
I did every class except main class because I cant read file after throw stack and queue.
public static void main(String[] args) throws IOException {
Stack stack = new Stack();
Queues queue = new Queues();
File stackfile = new File("stack.txt");
if (!stackfile.exists()) {
stackfile.createNewFile();
} else {
System.out.println("File is done");
}
FileReader r= new FileReader(stackfile);
BufferedReader reader = new BufferedReader(r);
String line = null;
Data data= new Data(); // this class have String name, surname and string number
int i=1;
while ((line=reader.readLine())!=null) {
{ if(line.trim().equals("#")){
stack.Push(data);
data=new Data();
i=1;
}
else{
if(i==1){
data.setNo(line);
}
else if(i==2){
data.setName(line);
}
else if(i==3){
data.setSurName(line);
}
i++;
}
}
}
stack.Push(data);
reader.close();
File queuefile = new File("queue.txt");
if (!queuefile.exists()) {
queuefile.createNewFile();
} else {
System.out.println("File is done");
}
BufferedReader read = null;
read = new BufferedReader(new FileReader(queuefile));
String lines = read.readLine();
while (lines != null) {
System.out.println("Read from queue: " + lines);
{ if(lines.trim().equals("#")){
queue.insert(data);
data=new Data();
i=1;
}
else{
if(i==1){
data.setNo(line);
}
else if(i==2){
data.setName(line);
}
else if(i==3){
data.setSurName(line);
}
i++;
}
}
}
queue.insert(data);
read.close();
}
}
Here is the corrected code. Your loop body did not do what you intended. If you want to split a text with a delimiter like #, use the split function of String. Here you can find out how to use split.
public static void main(String[] args) throws IOException {
Stack stack = new Stack();
Queues queue = new Queues();
File stackfile = new File("stack.txt");
if (!stackfile.exists()) {
stackfile.createNewFile();
} else {
System.out.println("File is done");
}
FileReader r = new FileReader(stackfile);
BufferedReader reader = new BufferedReader(r);
String line = null;
// Skip headline
reader.readLine();
while ((line = reader.readLine()) != null) {
String[] splitLine = line.trim().split("#");
if (splitLine.length == 3)
stack.Push(new Data(splitLine[1], splitLine[2], splitLine[0]));
}
reader.close();
File queuefile = new File("queue.txt");
if (!queuefile.exists()) {
queuefile.createNewFile();
} else {
System.out.println("File is done");
}
BufferedReader read = null;
read = new BufferedReader(new FileReader(queuefile));
// Skip headline
read.readLine();
while ((line = read.readLine()) != null) {
String[] splitLine = line.trim().split("#");
if (splitLine.length == 3)
queue.insert(new Data(splitLine[1], splitLine[2], splitLine[0]));
}
read.close();
}
I don't understand why this code won't read a .txt file then convert it to an array. I don't have the exact number of rows to begin with (to set the array) so I count the .txt files rows with a while loop.
This program should count the number of rows it imports then create a new array to copy & print the information to the console.
public class Cre{
public void openFile() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\file.txt"));
String line = in.readLine();
int i=0;
String linecounterguy = "null";
int count = 0;
while(line!= null) { ///to count number of rows///
linecounterguy = in.readLine();
count += 1;
}
String[] array = new String[count+1];
String line1 = "try";
while(line!= null)
{
line1 = in.readLine();
System.out.println(line1);
}
in.close();
for (int j = 0; j < array.length-1 ; j++) {
linecounterguy = in.readLine();
System.out.println(array[j]);
}
}
}
Main Class
> public class JavaApplication8 {
>
> /**
> * #param args the command line arguments
> */
> public static void main(String[] args) throws IOException {
>
>
> Cre k = new Cre();
> k.openFile();
>
>
> } }
Here is a little method that will get you started with reading a text file into an array of strings. Hope this helps!
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}
I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.